2014-01-29 2 views
2

문자열 내용의 단어 및 줄 수를 계산하고 싶습니다.문자열의 줄 및 단어 수를 계산하지 않습니다.

private int[] getLineAndWordCount(final String textContent) { 
    int wordCount = 0; 
    int lineCount = 0; 
    if (textContent.length() > 0) { 
     textContent = textContent.replace("\t", " "); 
     String[] newLineArrays = textContent.split("\n"); 
     lineCount = newLineArrays.length; 
     for (String newLineStr : newLineArrays) { 
      String[] wordsArray = newLineStr.trim().split(" "); 
      for (String word : wordsArray) { 
       if (word.length() > 0) { 
        wordCount++; 
       } 
      } 
     } 
    } 

    return new int[]{lineCount, wordCount}; 
} 

이 코드는 잘 작동하지만 exceution 동안 너무 많은 문자열을 생성합니다 : 여기 내 코드입니다. 그래서 똑같은 일을하는 다른 효과적인 방법이 있습니다. 감사.

+0

왜 그냥 문자열/파일의 모든 문자를 반복하지 않는 시도 할 수 있습니다? 공백, 탭 및 줄 바꿈 만 계산하면됩니다. – DaoWen

답변

2

java.util.Scanner을 사용해보세요.

Scanner textScanner = new Scanner(text); 
while (textScanner.hasNextLine()) { 
    linesCount++; 
    Scanner wordsScanner = new Scanner(textScanner.nextLine()); 
    while (wordsScanner.hasNext()) { 
     wordsCount++; 
     wordsScanner.next(); 
    } 
} 

자바 독 java.util.Scanner에 대한 : 예를 들어 http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

+0

스캐너가 내부적으로 부분 문자열을 생성하여 문제가 동일 함 –

0

이 방법을 시도 할 수 있습니다.

Scanner scanner=new Scanner(new File("Location")); 
    int numberOfLines=0; 
    StringTokenizer stringTokenizer=null; 
    int numberOfWords=0; 
    while (scanner.hasNextLine()){ 
     stringTokenizer=new StringTokenizer(scanner.nextLine()," "); 
     numberOfWords=numberOfWords+stringTokenizer.countTokens(); 
     numberOfLines++; 
    } 
    System.out.println("Number of lines :"+numberOfLines); 
    System.out.println("Number of words :"+numberOfWords); 
+0

스캐너가 내부적으로 부분 문자열을 만들어 문제가 동일 함 –

0

Usig 정규식은

String str = "A B C\n D E F\n"; 
     Pattern compile = Pattern.compile("\n"); 
     Matcher matcher = compile.matcher(str); 
     int count = 0; 
     while(matcher.find()){ 
      count++; 
     } 
     System.out.println(count);//2 
      count=0; 
    Pattern compile1 = Pattern.compile("\\s+"); 
     Matcher matcher1 = compile1.matcher(str); 

     while(matcher1.find()){ 
      count++; 
     } 
     System.out.println(count);//6 
0

또한이

int line=str.trim().split("\n").length; 
int words=str.trim().split("\\s+").length; 
관련 문제