输入包括1行字符串,以“.”结束,字符串中包含多个单词,单词之间以一个或多个空格隔开。
可能有多组测试数据,对于每组数据, 输出字符串中每个单词包含的字母的个数。
hello how are you.
5 3 3 3
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] s = br.readLine().split(" "); int i; for (i = 0; i < s.length - 1; i++) { System.out.print(s[i].length() + " "); } System.out.println(s[i].length() - 1); } }
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String str = sc.nextLine(); String[] strs = str.split(" "); for(int i=0;i<strs.length;i++){ if(i != strs.length-1){ System.out.print(strs[i].length()); System.out.print(" "); }else{ System.out.println(strs[i].length()-1); } } } } }
使用String的split方法,用正则表达式空格分开成小的字符串数组
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String str = in.nextLine();
String[] arr = str.split(" ");
for(int i = 0; i < arr.length; i++) {
if(i == arr.length - 1) {
System.out.print(arr[i].length() - 1);
}
else
System.out.print(arr[i].length() + " ");
}
}
}
}
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()){ String str = sc.nextLine(); int temp = 0; for (int i = 0; i < str.length(); i++){ if (str.charAt(i) != ' ' && str.charAt(i) != '.'){ temp++; } else if (str.charAt(i) == ' ' ){ System.out.print(temp + " "); temp = 0; continue; } else if (str.charAt(i) == '.'){ System.out.print(temp); temp = 0; break; } } System.out.println(); } } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); String[] result = str.split("\\s+"); for (int i = 0,n = result.length; i < n; i++) { if (i == n - 1) { System.out.print(result[i].length() - 1); } else { System.out.print(result[i].length() + " "); } } } } //不明白为什么通过率1.00%,醉醉的