这实际上是我的作业,问题是:
"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/