1. java統計單詞的個數
import java.util.Scanner;
public class Test40031 {
public static void main(String []args ){
int ri, repeat,count, word,i;
String line;
char c;
Scanner in=new Scanner(System.in);
repeat=(in.nextLine()).charAt(0)-'0'; //輸入repeat
for(ri=1; ri<=repeat; ri++){
line=in.nextLine(); //輸入一行字元
/*---------*/
count=Count(line);
System.out.println(count);
}
}
public static int Count(String str){
String[] str1=str.split(" ");
int count=str1.length;
return count;
}
}
2. 用java編寫應用程序,分析字元串,分別輸出字元串的單詞,並統計單詞個數
public class StringTest {x0dx0a public static void main(String[] args) {x0dx0a //定義一個測試字元串x0dx0a String testStr = "this is a test string";x0dx0a x0dx0a //將該字元串按空格分解辯碰歲成單吵嫌詞數組x0dx0a String[] words = testStr.split(" ");x0dx0a x0dx0a //輸出單詞個數x0dx0a System.out.println("該字元串一共有" + words.length + "個單詞!");x0dx0a x0dx0a //攜睜輸出每一個單詞x0dx0a for (int i = 0; i < words.length; i++) {x0dx0a System.out.println("該字元串的第" + (i+1) + "個單詞是:" + words[i]);x0dx0a }x0dx0a }x0dx0a}