简体   繁体   中英

How to count number of characters before a specific character?

I'm playing around on my spare time with C++ and I can't for the life of me seem to figure out how to count the number of characters before a specific one in a String.

For example:

Hello My Name \t is Bob!

I want it to count the number of characters (including spaces) before \\t .

Here is my attempt:

std::string test = "Hello My Name \t is Bob!"
std::string::size_type pos = line.find("\t");
int numOfCharacters = 0;

while (pos == std::string::npos) {
    numOfCharacters++;
    pos = pos + 1;
}

My understanding of .find() was that if npos was retrieved, that means you didn't find the text you were looking for, so I assumed it would keep going until I found \\t so it would kick out of the while-loop.

Your understanding of find() is correct, but your use of npos is wrong.

If the substring is found, you don't enter the loop, and numOfCharacters remains 0.

If the substring is not found, you loop without regard to the string's content until pos eventually increments to the point where it becomes npos (-1), and numOfCharacters will end up with a value that is nowhere near correct.

Maybe you were thinking of something more like this?

std::string test = "Hello My Name \t is Bob!"
std::string::size_type pos = line.find("\t");
std::string::size_type i = 0;
int numOfCharacters = 0;

while (i < pos)
{
    numOfCharacters++;
    i = i + 1;
}

That would be redundant, though. A string is 0-indexed, so a given character's index is also the number of characters that preceed it. You don't actually need a loop at all if you use find() :

std::string test = "Hello My Name \t is Bob!"
std::string::size_type pos = test.find("\t");
int numOfCharacters = static_cast<int>(pos);

If you are going to loop manually, then dont use find() at all:

std::string test = "Hello My Name \t is Bob!"
int numOfCharacters = -1;

for(std::string::size_type pos = 0; pos < test.size(); ++pos)
{
    if (test[pos] == '\t')
    {
        numOfCharacters = static_cast<int>(pos);
        break;
    }
}

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