JAVA- ---- 华为上级-----字符串最后一个单词的长度

题目描述

计算字符串最后一个单词的长度,单词以空格隔开。

输入描述:

 
  

一行字符串,非空,长度小于5000。

输出描述:

 
  

整数N,最后一个单词的长度。

示例1

输入

hello world

输出

5


解法1:

import java.util.Scanner;

public class Main {
	static Scanner scanner = new Scanner(System.in);
	public static void main(String[] args) {
		String string = scanner.nextLine();
		String[] strs = string.split(" ");
		
		System.out.println(strs[strs.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(" "));
        }    
    }
}


猜你喜欢

转载自blog.csdn.net/m0_37961948/article/details/80384049