1. 通过先分割字符串,再计算长度
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] str = line.split(" ");
System.out.println("The length of the last word is :");
System.out.println(str[str.length-1].length());
}
}
2.直接通过索引来计算
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s="";
while(input.hasNextLine()){
s=input.nextLine();
System.out.println(s.length()-1-s.lastIndexOf(" "));
}
}
}
3.利用输入流的特点
//输入流直接会记录最后一个字符串,因为单词之间是用空格隔开的
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
while(cin>>str);
cout<<str.size()<<endl;
return 0;
}