題目描述:
計算字符串最后一個單詞的長度,單詞以空格隔開。
輸入描述:
一行字符串,非空,長度小於5000。
輸出描述:
整數N,最后一個單詞的長度。
示例1:
輸入:
hello world
輸出:
5
代碼:
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner ( System.in );
String word = in.nextLine();
int n = word.lastIndexOf (" ");
if ( n == -1)
System.out.println( word.length() );
else {
String str = word.substring ( n ,word.length()-1 );
System.out.println(str.length());
}
}
}