题目要求
计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
示例1
输入:hello nowcoder
输出:8
说明:最后一个单词为nowcoder,长度为8
牛客原题
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da?tpId=37&&tqId=21224&rp=5&ru=/activity/oj&qru=/ta/huawei/question-ranking
实现代码
public class Main {public static void main(String[] args) {// 法一String str = "hello world";// 截取最后一个单词,计算它的长度: 首先从最后一个空格+1的下标开始截取,即单词首字母. 到字符串长度-1的下标结束,即单词末尾字母,计算截取单词长度int len = str.substring(str.lastIndexOf(" ") + 1).length();System.out.println(len);// 法二String str2 = "hello world";// 以空格分隔出不同字符串存放到数组里, 计算数组最后一个字符串的长度String[] s = str2.split(" ");System.out.println(s[s.length - 1].length());// 法三String str3 = "hello world";// 取得最后一个单词的首字母下标,该下标就是前面无关字符串的长度,然后用总长度减去该下标,即可得到最后单词长度System.out.println(str3.length() - (str3.lastIndexOf(" ") + 1));}
}
输出结果
5
5
5
觉得写得不错的话点个赞呗😊