问题
This is actually my homework and the question states:
"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.)"
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;
}
回答1:
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 ;-)
回答2:
This:
(contain =! string::npos)
^^
doesn't do what you think it does. Take a look at http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B.
Also, this:
contain = s.find(c, i);
doesn't do anything particularly useful (if all you're doing is incrementing i every iteration). You'll end up counting some occurrences multiple times.
[Note: You can solve the actual task much more cleanly by using count = std::count(s.begin(), s.end(), c).]
回答3:
You can do simply :
Instead of
contain = s.find(c, i);
if (contain =! string::npos )
{
count++;
}
Write
if(s[i] == c)
{
count++;
}
also, you can use this.
#include <algorithm>
int count = std::count(s.begin(), s.end(), c);
cout<<count;
回答4:
I think according to your problem statement.
changes the index value to 1 past the index of where the char was last found
Your while loop should be something like
while( 1 )
{
contain = s.find(c, i);
if (contain != string::npos )
{
count++;
i = contain + 1;
}
else
{
break;
}
}
来源:https://stackoverflow.com/questions/8870263/c-to-count-the-occurrences-of-a-char-in-a-string-using-findstr-index