繁体   English   中英

如何搜索字符串的一部分而不是全部

[英]how to search a part of a string not all of it

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

还有如何只比较2个与地区有关的字符?

我不知道直接使用标准库执行此操作的方法,但是您可以使自己的函数和strstr非常容易。

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

对于第二个问题:

还有如何只比较2个与地区有关的字符?

我不确定你是什么意思。 您是在问如何直接比较两个字符吗? 如果是这样,您可以像其他任何值一样进行比较。 if(str1 [n] == str2 [n]){...做某事...}

您可以使用std :: substr限制搜索范围:

std::string str = load_some_data();
size_t pos = str.substr(5).find('a');

我这样解决了

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)作为第二个或第三个方法的缓冲区

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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