如何统计一行字符中有多少个单词

package java程序员面试笔试宝典;

public class 题8_6_4统计一行字符中有多少个单词 {
	public static void main(String[] args) {
		String s="I am a student named Peng Zhao";
		wordCount(s);
	}
	public static void wordCount(String str){
		int i=0;
		int count=0;
		char[] chs=str.toCharArray();
		boolean flag=true;
		while(i<chs.length){
			if(chs[i]==' '){
				flag=true;
			}
			if(flag&&chs[i]!=' '){
				flag=false;
				count++;
			}
			i++;
		}
		System.out.println(count);
		
	}
}

猜你喜欢

转载自blog.csdn.net/m0_38068868/article/details/81739601