统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 请注意,你可以假定字符串里不包括任何不可打印的字符。 复制代码
示例:
输入: "Hello, my name is John" 输出: 5per", t = "title" 复制代码
思考:
这道题可以认为当前字符的前一个字符是空格,当前字符不为空格,则认为这是一个新的单词。 按照这个思想,循环判断字符串中的字符,计算单词数量。 复制代码
实现:
class Solution {
public int countSegments(String s) {
int count = 0;
//是否为空格
boolean isBlank = true;
for (int i = 0; i < s.length(); i++) {
//当前字符为空格
if (s.charAt(i) == ' ') {
isBlank = true;
} else {//当前字符不为空格
if (isBlank) {//前一个字符为空格
count++;//单词数+1
}
isBlank = false;
}
}
return count;
}
}复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Paradigms of Artificial Intelligence Programming
Peter Norvig / Morgan Kaufmann / 1991-10-01 / USD 77.95
Paradigms of AI Programming is the first text to teach advanced Common Lisp techniques in the context of building major AI systems. By reconstructing authentic, complex AI programs using state-of-the-......一起来看看 《Paradigms of Artificial Intelligence Programming》 这本书的介绍吧!
正则表达式在线测试
正则表达式在线测试
HEX CMYK 转换工具
HEX CMYK 互转工具