简体   繁体   中英

String comparison in C++

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. Can anyone help?

Thanks.

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

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')

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

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

You could also use the regular expression stuff added to the C++11 standard. See http://www.cplusplus.com/reference/regex/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM