5-26 单词长度 (15分)
你的程序要读入一行文本,其中以空格分隔为若干个单词,以.
结束。你要输出每个单词的长度。这里的单词与语言无关,可以包括各种符号,比如it's
算一个单词,长度为4。注意,行中可能出现连续的空格;最后的.
不计算在内。
输入格式:
输入在一行中给出一行文本,以.
结束
提示:用scanf("%c",...);
来读入一个字符,直到读到.
为止。
输出格式:
在一行中输出这行文本对应的单词的长度,每个长度之间以空格隔开,行末没有最后的空格。
输入样例:
It's great to see you here.
输出样例:
4 5 2 3 3 4
思路:
我刚开始的想法是分割字符串,但是如果字母之间有很多空格的话,那么就会出现错误,但是经过更改之后,最后一个测试点是格式错误。如代码1
代码2是正确的,它是循环输入字符,因为字符sc.next()与字符之间不能有空格.所以就不用考虑输入之间的空格,只用考虑句首和句尾的空格。我这在网上找了几个测试数据 供大家参考。
___________i
起始有空格i love.
有连续的空格.
单独一个点的情况。
代码1:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
char[] a = new char[s.length()];
int j = 0;
String[] num = s.split(" ");
for (int i = 0; i < s.length(); i++) {
a[i] = s.charAt(i);
if (a[i] == '.' && a[i - 1] == ' ') {
j = 1;
}
}
if (j == 1) {//句尾句号和单词之间有空格
for (int i = 0; i < num.length - 1; i++) {
if (num[i].length() != 0 && num[i] != ".") {
if (i < num.length - 2) {
System.out.print(num[i].length() + " ");
} else if (i == num.length - 2) {
System.out.println(num[i].length());
}
}
}
}else if(j == 0){//题目中的输入
for (int i = 0; i < num.length; i++) {
if (num[i].length() != 0 && num[i] != ".") {
if (i < num.length - 1) {
System.out.print(num[i].length() + " ");
} else if (i == num.length - 1) {
System.out.println(num[i].length()-1);
}
}
}
}
}
}
上述代码在测试的时候最后一个测试点是格式错误,有谁知道什么原因的可以告诉我一下,谢谢。
代码2:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int count = 0 ;
while(sc.hasNext()){//一直输入
String s = sc.next();
int l = s.length();
if(s.contains(".")){//判断输入的字符串中是否含有‘.’
count++;
l--;
if(l!=0&&count==1){
System.out.printf("%d",l);//输出时候和前面输出内容没有空格
}
else if(l!=0&&count!=1){
System.out.printf(" %d",l);//输出时候和前面输出内容有空格
}
}else{
count++;
if(count==1){
System.out.printf("%d",l);
}
else{
System.out.printf(" %d",l);
}
}
}
}
}
这个代码是正确的。