C ++使用find(str,index)计算字符串中char的出现次数, [英] C++ To count the occurrences of a char in a string using find(str, index)

查看:115
本文介绍了C ++使用find(str,index)计算字符串中char的出现次数,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上是我的家庭作业和问题状态:

This is actually my homework and the question states:


程序应该确定字符的次数
包含在字符串中(提示:使用
find(str,ƒind)方法搜索字符串。这个方法应该在循环中使用,
在0开始索引值,然后更改索引value to 1 past
上次找到字符的位置的索引。)

"The program should determine how many times the character is contained in the string. (Hint: Search the string by using the find(str,ƒind) method. This method should be used in a loop that starts the index value at 0 and then changes the index value to 1 past the index of where the char was last found.)"

但是它所做的就是计算字符串中有多少字符。新的C ++,所以我希望你们可以耐心与我。

This is what I've came up with but all it does is count how many character there is in the string. New to C++ so I hope you guys can be patient with me.

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string s;
    char c;
    size_t contain;
    int count = 0;
    cout << "Enter a string : ";
    getline(cin, s);
    cout <<"Enter a char : ";
    cin >> c;
    for(int i = 0; i < s.length(); i++)
    {
        contain = s.find(c, i);
        if (contain =! string::npos )
        {
            count++;
        }
    }
    cout << count <<endl;
    return 0;
}


推荐答案

我认为@ parapura的代码看nice'er like:

I think @parapura's code looks nice'er like this:

while((size_t contain = s.find(c,i)) != string::npos){
    count++;
    i = contain + 1;
}

它可以很好地解决问题; - )

and it solves the problem nicely ;-)

这篇关于C ++使用find(str,index)计算字符串中char的出现次数,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆