【问题标题】:how to search a part of a string not all of it如何搜索字符串的一部分而不是全部
【发布时间】:2013-10-15 01:55:05
【问题描述】:

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

还如何直接比较与语言环境相关的 2 个字符?

【问题讨论】:

    标签: c++ string search crt


    【解决方案1】:

    我不知道直接使用标准库的方法,但您可以很容易地创建自己的函数和 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] ) { ...做点什么... }

    【讨论】:

    • 感谢您的回答,但我认为更改数据内容以进行搜索并不是一个好习惯,如果另一个线程同时要求字符串或其长度怎么办? ?这会导致问题。
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的回答,那段代码的性能对我来说是个问题,substr 正在返回字符串一部分的新副本,我不需要复制即可搜索。
    【解决方案3】:

    我就这样解决了

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 2018-04-12
      相关资源
      最近更新 更多