首页 > 代码库 > Java程序员笔试面试之String5

Java程序员笔试面试之String5

.如何统计String中有多少个单词?

public class CountWord {
      public static int countWord(String s){
    	  int count=0;
    	  int word=0;
    	  
    	  for(int i=0;i<s.length();i++){
    		  if("".equals(s.charAt(i)))
    			  word=0;
    		  else if(word==0) {
    			  word=1;
    			  count++;
    		  }
    	  }
		return count;
      }
      public static void main(String args[]){
    	  String s="I am Jiang wei wei";
    	  System.out.print(s);
    	  System.out.println("单词的个数为:"+countWord(s));
    	  
      }
}


Java程序员笔试面试之String5