华为机试-1-字符串最后一个单词的长度
- 题目:计算字符串最后一个单词的长度,单词以空格隔开
输入描述:
一行字符串,非空,长度小于5000
输出描述:
整数N,最后一个单词的长度
- 示例:
输入:hello world
输出:5
- 考虑不全面代码,未考虑字符串末有空格以及只有一个单词的情况
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s ="";
while(sc.hasNext()){
s = sc.nextLine();
System.out.println(s.length()-s.lastIndexOf(" ")-1);
}
}
}
- 使用空格进行分割,并且正则匹配
import java.util.Scanner;
public class Main{
public static int lastword(String s){
//使用空格进行分割,“ +”为正则表达式
String st[] = s.split(" +");
return st[st.length-1].length();
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s ="";
while(sc.hasNext()){
s = sc.nextLine();
System.out.println(lastword(s));
}
}
}