C++使用find(str,index)计算字符串中char的出现次数

标签 c++ string count find

这实际上是我的作业,问题是:

"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++ 新手,所以我希望你们能耐心等待我。

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

最佳答案

这个:

(contain =! string::npos)
         ^^

并没有按照您的想法行事。看看http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B .

另外,这个:

contain = s.find(c, i);

没有做任何特别有用的事情(如果你所做的只是在每次迭代中递增 i )。您最终会多次计算某些事件。

[注意:您可以使用 count = std::count(s.begin(), s.end(), c).]

关于C++使用find(str,index)计算字符串中char的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8870263/

相关文章:

c# 我想知道字符串中的前 3 个字符是否为字母?

python - 按行计算非 na 值并将总计保存到 pandas 中的新变量

c++ - 对 typedef 用法感到困惑

c++ - const before AND after 函数

Java,返回字符串有问题

python - 使用python替换两个子字符串之间的字符串

mysql - 提高 MySQL 中的 count() 性能

mysql - 计算查询中的分钟数

c++ - 比多态性更简洁的代码替代方案

c++ - 如何在 long 变量中保留小时、分钟、秒?