【发布时间】:2010-11-13 17:15:15
【问题描述】:
示例:“select * from somewhere where x = 1”
我想在“somewhere”中找到以空格分隔的“where”,而不是“where”。在示例中,“where”由空格分隔,但也可以是回车、制表符等。
注意:我知道正则表达式会很容易做到(正则表达式等价物是“\bwhere\b”),但我不想为了这样做而将正则表达式库添加到我的项目中。
【问题讨论】:
示例:“select * from somewhere where x = 1”
我想在“somewhere”中找到以空格分隔的“where”,而不是“where”。在示例中,“where”由空格分隔,但也可以是回车、制表符等。
注意:我知道正则表达式会很容易做到(正则表达式等价物是“\bwhere\b”),但我不想为了这样做而将正则表达式库添加到我的项目中。
【问题讨论】:
如果您想使用纯 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 和 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 确实有重载了适当语义的流运算符,但是,正如我所说,我不知道。
【讨论】:
istream -- 那个我明白了。无论如何,我不知道CString 是否有任何流缓冲区。我从未使用过 MFC。
相当快,不需要构造繁重的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
【讨论】:
如果您使用带有 Feature Pack 的 Visual Studio 2008,您已经在 C++ 中拥有 std::tr1::regex。
【讨论】:
嗯,正则表达式是正确的答案。如果您不想包含正则表达式,则必须尝试自己实现一些正则表达式并搜索“ where ”。
我猜你唯一的其他选择是搜索“where”,然后检查匹配前后的字符,看看它们是否是空白字符。
【讨论】: