计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
#include <iostream> #include <cstdio> #include <cstring> #include <sstream> using namespace std; int main() { //方法一 string str,cur,pre; while(getline(cin,str)){//必须用循环,应对多行 istringstream line(str); while (line >> cur) { pre = cur; } cout << pre.length() << endl; } //方法二,没有考虑到多行情况,无法通过输出为5的测试用例 /* char c; int num = 0; while(1){ if(scanf("%c",&c) == EOF){ return 0; } if(c == ' '){ num = 0; } else if(c == '\n'){ break; } else{ num++; } } printf("%d\n",num);*/ //方法三--测试用例不止一个换行符 /* while(1)//没有这个会出错 { int num = 0; char s; while(1) { if(scanf("%c",&s) == EOF){ return 0; } if(s == ' '){ num = 0; } else if(s == '\n'){ break; } else { num++; } } printf("%d\n", num); }*/ return 0; }如代码所示,方法一和方法三,必须要多一层循环来考虑多行的情况,负责无法通过输出为5的测试用例。方法三是一开始没有考虑到输入为多行,参考别人的正确代码发现的,这个太坑了。
import java.util.*;
public class Main{
public static int lengthOfLast(String str) {
String[] s =str.split(" ");
return s[s.length-1].length();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.nextLine();
System.out.println(lengthOfLast(str));
}
}
}
str = input().strip().split() print(len(str[len(str)-1]))
// C++ //有些同学的答案没考虑到末尾有空格的情况,对于末尾有空格的都输出为0了。 //“hello world ”依然输出5. #include<iostream> #include<string> using namespace std; int main() { string s; while(getline(cin,s)){ int n=0,flag=1; for(int i=s.length()-1;i>=0;--i){//倒着计算 if(flag && s[i]==' '){//如果末尾有空格,先清除末尾空格 continue; } else if(s[i]!=' '){ flag = 0; ++n; } else{ break; } } cout << n << endl; } return 0; }
//最简单的方法就是,根本就不需要存储字符串,直接计算长度就可以了,也不需要动态的复杂的数据结构 #include <stdio.h> int main() { char ch; int n = 0; int flag = 0; while(1) { ch = getchar(); if(ch == '\n'){ break; } else if(ch != ' ') { if(flag == 0){ n = 0; flag = 1; } n++; } else { flag = 0; } } printf("%d\n", n); return 0; }
①类名必须是Main ②逻辑必须周全考虑null和空情况 ③几次没通过也有点郁闷,很简单的代码单独去写就会出错 哈哈 需要多敲代码类 么么哒~ import java.util.Scanner; public class Main{ public static int getLength(String str) { int length = 0; if (str != null && str.length() > 0) { String[] arr = str.split("\\s+"); length = arr[arr.length - 1].length(); } else { length = 0; } return length; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String str = scanner.nextLine(); int len = getLength(str); System.out.println(len); } } }