题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String line=scanner.nextLine();
StringBuffer sb=new StringBuffer(line);
String reversedLine=sb.reverse().toString();
int i=0;
while(i<reversedLine.length() && reversedLine.charAt(i)!=' '){
i++;
}
System.out.println(i);
}
}
字符串最后一个单词的长度,很容易想到逆转字符串,然后算这个逆转字符串从开始到出现第一个空格的字符有多少个,即是最后一个字符串的长度
凡岛公司福利 319人发布
查看5道真题和解析