来看看这题

来源:百度知道 编辑:UC知道 时间:2024/05/28 06:50:15
输入一个字符串,统计有多少个单词?单词之间要用空格隔开

代码如下:

public class Test
{

public static int wordCount( String args )
{
return args.split(" ").length; // 根据空格把字符串分为字符数组
}

public static void main( String[] args )
{
System.out.println(wordCount("Go to school")); // 输出结果为3个单词
}
}

public class CharNum{
public void printchard(String str){
int len=str.length();//String的 length()方法获得字符长度
System.out.println(str+"的长度是:"+len);
StringBuffer buf=new StringBuffer();//使用StringBuffer
for(int i=0;i<len-1;i++){
buf.append(str.subString(i,(i+1)));//使用String的subString(index,last);方法窃取字符
buf.append(" ");//连接上" "空格
}
System.out.println("连接上空格后"+buf.toString());
}
public static void mian(String[] ags){
CharNum test=new CharNum();
String str="abc";
test.printchard(str);
}
}