在一个CString找到一个空格分隔单词的最佳方法(Best way to find a white

2019-07-30 18:02发布

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

我想找到空格分隔的“ where ”,而不是“ where ”内“ somewhere ”。 在该示例中“其中”由空格分隔,但它可能是回车,制表符等

注:我知道正则表达式将可以很容易做到(正则表达式相当于将“ \bwhere\b ”),但我不希望一个正则表达式库添加到我的项目只是为了做到这一点。

Answer 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


Answer 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确实与适当的语义过载流运营商,但是,正如我所说,我不知道。



Answer 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


Answer 4:

如果您在使用Visual Studio 2008功能包你已经拥有的std :: TR1 ::正则表达式在C ++中。



Answer 5:

好了,正则表达式是正确答案。 如果你不希望包括正则表达式,你将不得不尝试和实施正则表达式一点自己并搜索“其中”。

我猜你唯一的选择是搜索“在哪里”,然后检查字符之前和比赛结束后,看他们是否有空格字符。



文章来源: Best way to find a whitespace-delimited word in a CString
标签: c++ mfc