Reputation:
I am trying to find the number of i's in a string. Here is my code:
string str = "CS445isaninterestingcourse";
int num = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.substr(i, i + 1) == 'i')
num++;
}
But I get errors.
Upvotes: 1
Views: 217
Reputation: 10777
substr method returns a string. You are trying to compare a string with a char, this is invalid. Just change 'i' with "i". Also, you should say str.substr(i,1) instead of str.substr(i,i+1). You can try this:
string str="CS445isaninterestingcourse";
int num=0;
for(int i=0; i<str.length();i++)
{
if(str.substr(i,1)=="i")
num++;
}
or equivalently, you could say that
if(str.at(i)=='i')
Upvotes: 4
Reputation: 2532
Since the question mentions C++ explicitly:
#include <iostream>
#include <algorithm>
int main(int argc, const char * argv[])
{
std::string str = "CS445isaninterestingcourse";
size_t i = std::count(str.begin(), str.end(), 'i');
std::cout << "Number of i's:" << i << "\n";
return 0;
}
Upvotes: 7
Reputation: 61900
Use std::count
. That's what it's for:
int num = std::count(std::begin(str), std::end(str), 'i');
Upvotes: 3
Reputation: 3135
You could also use the regular expression stuff added to the C++11 standard. See http://www.cplusplus.com/reference/regex/
Upvotes: 0