Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
思路:1、采用java内部函数,以空白符分割字符串
2、C语言处理,遍历每个字符,要注意字符串的头部,尾部空格。
java代码:
class Test{
public int strSegmentsNumber(String s){
if(s.trim()<=0){//排除空串和以空格组成的字符串
return 0;
}
return s.trim().split("\\s+").length;//"\s"是正则表达式中所有的空白符,"+"不止一个空白符
}
}
c代码:
int countSegments(char* s) {
int i=0,j=0,flag=0,k=0;
while(s[i]!='\0'){
//去掉头部空格和内部出现的多个空白符
if(i!=0&&s[i]==' '&&s[i-1]!=' '){
j++;
flag=1;
}
if(s[i]==' '){//字符串中的空格数
k++;
}
i++;
}
//去掉末尾的空格
if(s[i-1]==' '){
j=j-1;
}
if(flag==0){
if(i>0&&j==0&&k==0){//出现"hello"这种情况是
return j+1;
}else{//出现" "这种字符串的情况
return 0;
}
}else{
return j+1;
}
}