题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
http://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
import java.util.Scanner;
/**
* 从后往前计数,两种情况:一个单词;... 单词+空格+单词 ...
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int length = str.length();
for (int count = 0, i = length -1; i >= 0; i-- ) {
if (str.charAt(i) == ' ') {
System.out.println(count);
break;
} else if (count == length - 1){
System.out.println(length);
} else {
count++;
}
}
}
}