0

在 C++ 中,如何仅搜索从 startIndex 开始并在一些字符数之后结束的字符串的一部分。在某些情况下,我只需要在前 5 个字符中搜索特殊字符或字符串,为什么我必须遍历整个字符串,它可能是 1000 个字符或多个字符。我在 c++ 运行时库中所知道的,所有函数都不支持类似的东西,例如strchr它将搜索所有字符串,我不想我想要比较字符串的特定部分从 [] 到 [ ]。我已经看到使用该问题的解决方案wmemchr解决该问题的方法,但我需要它依赖于当前选择的语言环境,如果有人知道如何做到这一点,我将不胜感激。

另外,如何直接将 2 个字符与语言环境进行比较?

4

3 回答 3

0

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

于 2013-10-15T03:57:09.793 回答
0

您可以使用std::substr来限制您的搜索区域:

std::string str = load_some_data();
size_t pos = str.substr(5).find('a');
于 2013-10-15T13:01:10.290 回答
0

我就这样解决了

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

并指定传递给 (buffer + startIndex) 的起始索引作为第二个或第三个方法的缓冲区

于 2013-10-18T11:38:25.130 回答