题目概述(简单难度)
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: “Hello, my name is John”
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 “Hello,” 算作 1 个单词。
附上leetcode链接:
点击此处进入leetcode
思路与代码
思路展现
思路1(纯split方法)
对于这种简单题,明显是要考查对边界条件的考虑,比如给定的字符串可能开头有空格、中间有连续的空格,结尾有空格
,等等。
举例1:此时str这个字符串开头和结尾都有空格,经过划分后得到的数组第一个元素和最后一个元素都是空字符串
public class string {
public static void main(String[] args) {
String str = " spit hello sorld ";
String[] strings = str.split(" ");
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
}
上述代码的输出结果为:
举例2:此时前后各有一个空格,中间有两个空格
public class string {
public static void main(String[] args) {
String str = " spit hello sorld ";
String[] strings = str.split(" ");
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
}
输出结果为:
可以看到使用空格分隔的时候,除了两边,中间那部分还会多出来一个空字符串.
针对这道题目,我们最保险的做法
就是先调用库函数按空格分割字符串
,再判断每个字符串本身是不是等于空字符串
。
代码示例
class Solution {
public int countSegments(String s) {
String[] str=s.split(" ");
int count=0;
for(int i = 0;i < str.length;i++){
if(!str[i].equals("")){
count++;
}
}
return count;
}
}
思路2(trim方法+split方法)
使用trim方法先去掉字符串两边的空格,然后再使用split方法去掉字符串中间的空格,最后再统计非空格的字符
代码示例
class Solution {
public int countSegments(String s) {
//先去掉字符串两边的空格
String str1=s.trim();
//再去掉字符串中间的空格
String[] str=str1.split(" ");
int count=0;
for(int i = 0;i < str.length;i++){
//判断是否为空字符串
if(!str[i].equals("")){
count++;
}
}
return count;
}
}
总结
还是split方法和trim方法的运用,强加练习