求字符串最后一个单词的长度

来源:互联网 发布:中软国际php培训怎么样 编辑:程序博客网 时间:2024/05/20 10:13

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;
}