Question

in c++ how to search just a part of a string starting from startIndex and ending after some count of chars. in some cases I just need to search the first 5 chars for a special char or string why will I have to come over the whole string it may be 1000 chars or multiples of that. what I know in c++ run time library, all functions don't support something like that for example strchr it will search all of the string, I don't want that I want to compare a specific part of the string from [] to []. I've seen a solution for that problem using wmemchr but I need it to be dependent on the currently selected locale, if anybody know how to do that, I'd be grateful.

Also how to compare just 2 chars directly regarding to the locale?

Was it helpful?

Solution 3

I solved it like that

int64 Compare(CHAR c1, CHAR c2, bool ignoreCase = false)
{
    return ignoreCase ? _strnicoll(&c1, &c2, 1) : _strncoll(&c1, &c2, 1);
}

int64 IndexOf(const CHAR* buffer, CHAR c, uint count, bool ignoreCase = false)
{
    for (uint i =0; i < count; i++)
    {
        if (Compare(*(buffer + i), c, ignoreCase) == 0)
        {
            return i;
        }
    }
    return npos;
}

int64 LastIndexOf(const CHAR* buffer, CHAR c, uint count, bool ignoreCase = false)
{
    while(--count >= 0)
    {
        if (Compare(*(buffer + count), c, ignoreCase) == 0)
        {
            return count;
        }
    }
    return npos;
}

npos = -1

and to specify the start index pass to (buffer + startIndex) as the buffer to the second or the third method

OTHER TIPS

I'm not aware of a way to do this directly with a standard library, but you could make your own function and strstr pretty easily.

/* Find str1 within str2, limiting str2 to n characters. */
char * strnstr( char * str1, const char * str2, size_t n )
{
    char * ret;
    char temp = str1[n]; // save our char at n
    str2[n] = NULL; // null terminate str2 at n
    ret = strstr( str1, str2 ); // call into strstr normally
    str2[n] = temp; // restore char so str2 is unmodified
    return ret;
}

For your second question:

Also how to compare just 2 chars directly regarding to the locale?

I'm not sure what you mean. Are you asking how to compare two characters directly? If so, you can just compare like any other values. if( str1[n] == str2[n] ) { ...do something... }

You can use std::substr to limit your search area:

std::string str = load_some_data();
size_t pos = str.substr(5).find('a');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top