简体   繁体   中英

C++ Find last char in char array

Basically I'm trying to find last char in a char* array. eg; I have this string:

"This is a long string with many other \"characters\". Hehehe"

I tried to use this:

int findLast (const char* buffer, int pos, char character, int size)
{
    int last = 0;

    for (int i = pos; i < size; i++)
    {
        if (buffer[i] == character)
            last = i;
        if (buffer[i] == '\n')
            return last;
    }

    return last;
}

Like this:

int lastCharPos = findLast ( charArray, ftell(file), '"', charSize );

In the charArray we have:

"This is a long string with many other \"characters\". Hehehe"

findLastChar returns the pos of " that comes after "characters", but the last one should be after Hehehe.

The idea is to return the position of the last "char" specified by user request, however it doesn't work.

I'm trying to use it with this string:

"Welcome to Stackoverflow!\nWe seriously hope you have a \"great\" time."

It returns (the code says the " after great is the last one, but as you can see in the given string, it's not):

"Welcome to Stackoverflow!\nWe seriously hope you have a \"great\"

Trying to use it to search for "

this is tagged c++, so dont use char*

#include <string>

int findLastPos( std::string s, char c )
{
     return s.rfind( string(1,c) );
}

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