计算字符串最后一个单词的长度,单词以空格隔开。 java算法

时间:2021-03-28 22:26:58
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s = in.nextLine();
CodeLength(s); }
public static void CodeLength(String s){
String [] str = s.split(" ");
int length = str.length;
System.out.println(str[length-1].length());
}
}

方法二:

import java.util.*;
public class Main{
public static int lengthOfLast(String str) {
String[] s =str.split(" ");
return s[s.length-1].length();
} public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.nextLine();
System.out.println(lengthOfLast(str));
}
}
}