2017-12-17 6 views
-1
내가 문자열에서 단어의 수를 찾기 위해 코드를 작성했다

단어와 코드는 다음과 같습니다 :자바 카운트 문자열

package exercises; 

import java.util.Scanner; 

public class count { 

    public static int countwords(String str){ 
     int count=0; 
     String space=""; 
     String[] words=str.split(space); 
     for(String word:words){ 
      if(word.trim().length()>0){ 
       count++; 
      } 

     } 
     return count; 
    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     System.out.println("Enter the string"); 
     Scanner input=new Scanner(System.in); 
    String s=input.nextLine(); 
    System.out.println(countwords(s)); 

    } 

} 

과 연습을하고 내가이

package exercises; 

import java.util.Scanner; 

public class count { 

    public static int countwords(String str){ 
     int count=0; 
     String space=""; 
     String[] words=str.split(space); 
     for(String word:words){ 
      if(word.trim().length()>0){ 
       count++; 
      } 

     } 
     return count; 
    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     System.out.println("Enter the string"); 
     Scanner input=new Scanner(System.in); 
    String s=input.nextLine(); 
    System.out.println(countwords(s)); 

    } 

} 
로 다시 한 번이 코드를 작성

나는이 코드에 대해 다른 코드의 출력이 왜 다른지 궁금합니다. 코드를 한 줄씩 확인했지만이 두 코드의 출력이 다른 이유는 무엇입니까? 누구든지 도와주십시오

+1

("") '... 당신이 (오히려 공간보다 빈 문자열을 분할 할 이유 또는 공백)? –

답변

0
String space=""; 

잘못되었습니다. 빈 문자열이고 잘못 사용됩니다.

당신은 더 나은

 String space="\\s+"; 

또는

String space=" "; 

정규식 "\\ S +"입니다 "하나 이상의 공백 기호"

이 분할 문자열 ""입니다
+0

"\\ s +"을 (를) 의미하지 않습니까? –

+0

예. 죄송합니다, 당신 말이 맞아요 – GuyKhmel

2

때문에, 모든 문자를 사용 단어로 추출됩니다.

String space="";에서 String space=" "; 또는 String space="\\s+";으로 변경하면 가도 좋습니다.

정규 표현식 도구 \\s+은 하나 이상의 공백이 나온 후에 문자열을 분할해야 함을 나타냅니다.

+0

고맙습니다 works.Also이 코드를 더 좋게 만드는 제안? 또한 문자열에서 고유하고 중복되는 단어를 찾기 위해 추가해야 할 내용. –

+0

@ppkumar 언제든지 :) –

0

또 다른 옵션은 그런 일이 될 수 :

당신은 str.split`나를 잃어
public static void main(String[] args) { 
    System.out.println("Enter the string"); 
    Scanner input=new Scanner(System.in); 
    String line=input.nextLine(); 
    System.out.println(Arrays.stream(line.split(" ")).count()); 
}