2012-03-05 4 views
1

나는 String을 가지고 있으며 주어진 인덱스에서 그것을 자르고 싶다. 시나리오에는 문자열에 HTML 태그가 포함될 수 있으며 클리핑하는 동안 해당 태그를 건너 뛸 수 있습니다.주어진 인덱스에 문자열 자르기

"Les pirates ont<br/>attaqué des douzaines de sites Web français"; 

그리고 내가 Les pirates ont<br/>attaqué...를 얻을 수 있도록 25을 클립 할 :

예를 들어 문자열 인 경우. 또한 중간에서 단어를 잘라낼 수 없지만 클리핑 지점의 문자가 공백이 아니라면 공백을 찾을 수 없을 때까지 그 점에서 문자열을 역 추적해야합니다. 어떤 공간이라도 발견되면 나는 그 색인까지자를 것이다. 여기

내가 노력 코드이지만, 그것은 무한히 반복된다

public class Test { 

    private String value = "Les pirates ont<br/>attaqué des douzaines de sites Web français"; 
    private int clipAt = 25; 

    public Test() { 
     run(); 
    } 

    private void run() { 
     String elipsis = "..."; 
     int originalLength = value.length(); 
     int cliplength = clipAt - elipsis.length(); 
     String clipedValue = value; 

     if (originalLength > cliplength) { 
      char character = value.charAt(cliplength + 1); 

      while (character != ' ') { 
       if(character == '>'){     
        cliplength += count(value.substring(0, cliplength+2));  
       } 

       cliplength = cliplength - 1; 
       character = value.charAt(cliplength + 1);     

      } 
      clipedValue = value.substring(0, cliplength + 1)+elipsis; 
     } 
     System.out.println(clipedValue); 
    } 

    private int count(String str){  
     int length = str.length() - 1; 
     char character = str.charAt(length); 
     int count = 0; 
     while(character != '<'){ 
      length--; 
      character = str.charAt(length); 
      count++; 
     } 
     System.out.println(count); 
     return count; 
    } 

    public static void main(String... args){ 
     new Test(); 
    } 
} 

모든 정보는 나에게 매우 도움이 될 것입니다.

감사합니다.

답변

1

구문 분석 html은 쉬운 작업이 아닙니다. HTML은 정규 언어가 아니므로 정규 표현식이 도움이되지 않습니다 ... 그러나 htmlunit이 도움이 될 수 있습니다. Check the options for HTML scrapping

행운을 비네!

1

텍스트가 "I am feeling <html> too good </html> today."이라고 말하면서 약간의 혼란이 생기고, 이제는 14시에 클립을 사용한다고 가정하면이 문자열 "I am feeling <html>..." 또는 다른 것을 반환하겠습니까?

public class ClipText 
{ 
    private void clipString(String text, int endIndex) 
    { 
     int i = endIndex; 
     String result = new String(); 
     do 
     { 
      if (Character.isWhitespace(text.charAt(endIndex))) 
      { 
       result = text.substring(0, endIndex); 
       result = result + "..."; 
       break; 
      } 
      else 
      { 
       endIndex++; 
       i++; 
      }    
     }while(i <= endIndex); 
     System.out.println("Result : " + result); 
    } 

    public static void main(String... args) 
    { 
     String text = "Les pirates ont<br/>attaqué des douzaines de sites Web français"; 
     int endIndex = 6; 
     new ClipText().clipString(text, endIndex); 
    } 
} 
:

것은이 코드를 시도, 희망이 부분을 해결합니다

관련 문제