tags:

views:

718

answers:

5

example: "select * from somewhere where x = 1"

I want to find the whitespace-delimited "where", but not the "where" within "somewhere". In the example "where" is delimited by spaces, but it could be carriage returns, tabs etc.

Note: I know regex would make it easy to do (the regex equivalent would be "\bwhere\b"), but I don't want to add a regex library to my project just to do this.

A: 

Well, regex is the correct answer. If you don't want to include regex, you will have to try and implement a bit of regex yourself and search for " where ".

Your only other option I guess would be to search for "where", then check the character before and after the match to see if they are whitespace characters.

rikh
A: 

If you are using Visual Studio 2008 with Feature Pack you already have std::tr1::regex in C++.

Cristian Adam
+3  A: 

I don't know the first thing about MFC and CString, but in plain C++ I'd stuff that string into an std::istringstream and read from that into a string:

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

I suppose CString does have stream operators overloaded with the appropriate semantics, but, as I said, I don't know it.

sbi
The extraction requires an ostream, and will read from any ostreambuf. You'd need an ostreambuf over CString to do this.
MSalters
s/ostream/istream/g of course.
MSalters
@MSalters: Um, am I brain-farting here or is that you? :)
sbi
@MSalters: Ah, `istream` -- _that_ I understand. Anyway, I wouldn't know whether there's any stream buffers for `CString`. I never used MFC.
sbi
+2  A: 
Kirill V. Lyadvinsky
this one actually enables to search for more complex expressions like "GROUP BY"
djeidot
Yes, my solution is universal and doesn't require additional memory.
Kirill V. Lyadvinsky
+1  A: 

If you wanted to use the pure MFC method of string manipulation, then this should work:

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
Alan
I like this answer. It uses pure MFC, which I prefer, and also enables to do case insensitive searches. sbi's and JIa3ep's answers are also pretty good, though.
djeidot
eewwwwwwwww - MFC
jkp