【问题标题】:Best way to find a whitespace-delimited word in a CString在 CString 中查找以空格分隔的单词的最佳方法
【发布时间】:2010-11-13 17:15:15
【问题描述】:

示例:“select * from somewhere where x = 1

我想在“somewhere”中找到以空格分隔的“where”,而不是“where”。在示例中,“where”由空格分隔,但也可以是回车、制表符等。

注意:我知道正则表达式会很容易做到(正则表达式等价物是“\bwhere\b”),但我不想为了这样做而将正则表达式库添加到我的项目中。

【问题讨论】:

    标签: c++ mfc


    【解决方案1】:

    如果您想使用纯 MFC 字符串操作方法,那么这应该可以:

    CString strSql = _T("select * from somewhere where x = 1");
    
    int nTokenPos = 0;
    CString strToken = strSql.Tokenize(_T(" \r\n\t"), nTokenPos);
    
    while (!strToken.IsEmpty())
    {
        if (strToken.Trim().CompareNoCase(_T("where")) == 0)
            return TRUE; // found
        strToken = strSql.Tokenize(_T(" \r\n\t"), nTokenPos);
    }
    
    return FALSE; // not found
    

    【讨论】:

    • 我喜欢这个答案。它使用我更喜欢的纯 MFC,并且还可以进行不区分大小写的搜索。不过,sbi 和 JIa3ep 的回答也不错。
    【解决方案2】:

    我不知道关于 MFC 和 CString 的第一件事,但在纯 C++ 中,我会将那个字符串填充到一个 std::istringstream 中并从中读取到一个字符串中:

    std::istringstream iss("select * from somewhere where x = 1");
    std::string word;
    do {
      iss >> word;
      if( !iss ) throw "blah blah!";
    } while( word != "where" );
    

    我想CString 确实有重载了适当语义的流运算符,但是,正如我所说,我不知道。

    【讨论】:

    • 提取需要一个 ostream,并且会从任何 ostreambuf 中读取。你需要一个 CString 上的 ostreambuf 来做到这一点。
    • @MSalters:啊,istream -- 那个我明白了。无论如何,我不知道CString 是否有任何流缓冲区。我从未使用过 MFC。
    【解决方案3】:

    相当快,不需要构造繁重的istringstream 对象。

    CString str = L"select * from somewhere where x = 1";
    CString to_find = L"where";
    int i =0;
    while ( i < str.GetLength() ) {
        i = str.Find(to_find, i);
        if ( i == -1 ) break;
        if ( (i == 0 || !isalpha(str[i-1])) && (i == str.GetLength()-to_find.GetLength() || !isalpha(str[i+to_find.GetLength()])) ) break;
        i+=to_find.GetLength();
    }
    if ( i >= 0 && i < str.GetLength() ) // found
    else // not found
    

    【讨论】:

    • 这个实际上可以搜索更复杂的表达式,例如“GROUP BY”
    • 是的,我的解决方案是通用的,不需要额外的内存。
    【解决方案4】:

    如果您使用带有 Feature Pack 的 Visual Studio 2008,您已经在 C++ 中拥有 std::tr1::regex

    【讨论】:

      【解决方案5】:

      嗯,正则表达式是正确的答案。如果您不想包含正则表达式,则必须尝试自己实现一些正则表达式并搜索“ where ”。

      我猜你唯一的其他选择是搜索“where”,然后检查匹配前后的字符,看看它们是否是空白字符。

      【讨论】:

        猜你喜欢
        • 2010-12-01
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多