434.Number of Segments in a String(String-Easy)

转载请注明作者和出处: http://blog.csdn.net/c406495762

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

题目:返回字符串有几个字段。

思路:很简单,空格就是区分字段的标志。

  • 自己写个trim()函数,用于去掉字符串两端的空格;
  • 判断字符串是会否为空,为空返回0,代表有0个字段;
  • 使用空格标志区分字段:上一个字符为空格,当前字符不为空格,字符段计数加一。

Language:cpp

class Solution {
public:
    //去掉字符串两端的空格
    string& trim(string &s) {
        if (s.empty()) {
            return s;
        }
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
        return s;
    }

    int countSegments(string s) {
        //字符串为空,返回0
        if (trim(s).empty()) {
            return 0;
        }
        int ans = 1;
        s = trim(s);   
        for (int i = 0; i < s.length(); i++) {
            //当上一个字符是空格,当前字符不是空格时,则为一个字段
            if (s[i-1] == ' ' && s[i] != ' ') {
                ans++;
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack-Cui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值