分为两种解法
第一种直接split以“ {1,}”为分隔符给分割了,因为空格可能>=1个牛客里面测试用例太少只有一个空格的情况
第二种解法字符串转化为字符数组,计算倒数字符串长度l,以及倒数第一个空格位置count(还有只给一个字符串没有空格的情况),返回l-count-1(或者l)
第一种需要熟悉java的API才能如此简单的解出来
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = null; //字符串赋值必须要初始化
// 注意 hasNext 和 hasNextLine 的区别
//输入带空格的字符串是nextline
//原来这个hasnextline是每次输入都需要输出啊 妈的 根本出不来 想要出来 还只能换成hasnext
while (in.hasNextLine()) { // 注意 while 处理多个 case
a = in.nextLine();
String[] str=a.split(" {1,}");
int l=str.length;
System.out.println(str[l-1].length());
}
}
}
第二种解法复杂,但是学会了也很受用
import java.util.Scanner;
public class math0030HJ1字符串最后一个单词长度 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = null; //字符串赋值必须要初始化
while (in.hasNextLine()) {
a = in.nextLine();
//字符串转化为字符
char[] ch = a.toCharArray();
//获取字符的长度大小
int l = ch.length;
int count = 0;
//然后找到倒数第一个空格的位置记录下来
for (int i = l - 1; i >= 0; i--) {
if (ch[i] == ' ') {
count = i;
break;
}
}
//找到倒数第一个空格count之后,然后返回l-1-count
if(count==0){
//防止没有空格的字符串对吧
System.out.print(l);
}else{
System.out.print(l-1-count);
}
}
}
}
文章介绍了两种在Java中获取字符串最后一个单词长度的方法。第一种利用split方法以连续空格为分隔符,第二种将字符串转为字符数组,遍历找到倒数第一个空格位置。两种方法各有特点,适用于不同情况。
&spm=1001.2101.3001.5002&articleId=129389165&d=1&t=3&u=2ecebb3c5f52481b9151892a6dc33dc7)
544

被折叠的 条评论
为什么被折叠?



