user2110714
user2110714

Reputation:

Count occurences of a character in a string

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

Answers (4)

yrazlik
yrazlik

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

Christian Garbin
Christian Garbin

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

Qaz
Qaz

Reputation: 61900

Use std::count. That's what it's for:

int num = std::count(std::begin(str), std::end(str), 'i');

Upvotes: 3

denver
denver

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

Related Questions