描述
计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
输入描述:
输入一行,代表要计算的字符串,非空,长度小于5000。
输出描述:
输出一个整数,表示输入字符串最后一个单词的长度。
示例1:
输入:hello nowcoder,输出:8,说明:最后一个单词为nowcoder,长度为8
java代码如下:
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
// 示例输入
Scanner in = new Scanner(System.in);
String inputString = in.nextLine();
in.close();
// 调用函数并打印结果
int lastWordLength = getLastWordLength(inputString);
System.out.println(
lastWordLength); // 输出应该是 8,因为 "Overflow" 的长度是 8
}
public static int getLastWordLength(String s) {
// 去除字符串末尾可能存在的空格
s = s.trim();
// 如果字符串为空,则没有单词,返回0
if (s.isEmpty()) {
return 0;
}
// 从字符串末尾开始向前寻找第一个空格的位置
int lastIndex = s.lastIndexOf(' ');//里面的参数可以用Unicode码表示
// 如果没有找到空格,则整个字符串就是一个单词
if (lastIndex == -1) {
return s.length();
}
// 返回最后一个单词的长度,即最后一个空格的位置之后到字符串末尾的长度
return s.length() - lastIndex - 1;
}
}