C ++中字符串中的段数
因此,如果输入就像“你好,我喜欢编程”,那么输出将为4,因为有4个段。
为了解决这个问题,我们将遵循以下步骤-
n:=0
对于初始化i:=0,当i<s的大小时,更新(将i增加1),执行-
(将i增加1)
(将n增加1)
如果s[i]不等于空格,则-
而(i<s的大小,s[i]不等于空格),则执行-
返回n
例
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countSegments(string s) {
int n = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] != ' ')
n++;
while( i < s.size() && s[i] != ' ')
i++;
}
return n;
}
};
main(){
Solution ob;
cout << (ob.countSegments("Hello, I love programming"));
}输入项
"Hello, I love programming"
输出结果
4
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短