给一个字符串s,由若干单词组成,输出字符串中最后一个单词的长度
public class test {
public static void main(String[] args) {
//倒着遍历,直到遇到空格为止,遍历的次数就是单词的长度
//注:如果要从键盘录入,需要使用.nextLine,因为.next遇到空格和换行符会自动结束
String str="hello world";
StringBuilder sb=new StringBuilder();
sb.append(str).reverse();
int count=0;
for (int i = 0; i < sb.length(); i++) {
char c=sb.charAt(i);
if (c==' '){
break;
}
count++;
}
System.out.println(count);
}
}