434. Number of Segments in a String--leetcode

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;
    }  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值