题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
int lastLength = 0;
char[] chars = input.toCharArray();
for (int i = chars.length - 1; i >= 0; i--) {
if (chars[i] != (char) 32) {
lastLength++;
} else {
break;
}
}
System.out.print(lastLength);
}
}
解题思路:
将输入的字符串转换为字符数组,倒着遍历该数组,如果遇到不是空格的字符,将统计变量lastLength加1,否则结束遍历。
注意:
在判断是否是空格时,使用了ASCII码进行转换。chars[i] != (char) 32。
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));
}
}
}
