i have a string "8120, 8120NGE, 8120NG, 8130, 8130NG, 8130NGE".
And i have a char* (0x0012d094 "8130")
I want to see if the "8130" is in. That exact word.
So i am using
istringstream iss(boards);
string token;
AVBOOL foundBool=FALSE;
while(std::getline(iss, token, ','))
{
const char * compareToken = token.c_str();
token.compare(board); // with that : it doesn't work cause "8130" is not equal 0x0012d094 "8130"
if(strcmp(compareToken,board)==0) //with that it doesnt work cause 0x0012cef0 " 8130" is not equal 0x0012d094 "8130"
{
foundBool=TRUE;
}
}
So the question is how do i compare a string with a char * .
Do I need to convert the char into a string and then use string.compare OR Do i need to convert the string into a char and use strcmp? OR Do i need to do something else?
I am kind of lost here.
You can use both.
I prefer use .c_str() method with strcmp() C function because it doesn't create an string object.
how about boards.find( token )
if you need it to not have alphanumeric characters after, just check if there is such
and if so search again from that position
cheers & hth.,
Would using a std::set suit your needs ?
std::set<std::string> boards;
while (std::getline(iss, token, ',')) {
boards.insert(token);
}
if (boards.find(board) != boards.end()) {
// we found it
}
Note that this does not take into account whitespace that might be in the tokens.
Your question sounds like you're confused about comparison - you can compare a string and a const char* just fine! Both string::compare(const char*) and strcmp will return 0 when the contained characters are equal:
string one = "pl";
string two = "ex";
const char* too = "plex";
int main()
{
string three = one + two;
cout << three.compare(too) << endl;
cout << strcmp(three.c_str(), too) << endl;
}
will print
0 0
Your actual application problem is that you probably want to split a string by ", ", which you can't do with standard library tools. If you can't generally get rid of the spaces as mentioned in Mazurov's answer you will need a tokenizer that accepts string separators.
I think you need to re-write your code so that it strips whitespace before reading tokens. You can adjust your loop as such:
istringstream iss(boards);
string token;
bool found = false;
while((iss >> std::ws) && std::getline(iss,token,','))
{
found |= (token == board);
}
The loop can also be optimized to stop when the token is found:
while(!found && (iss >> std::ws) && std::getline(iss,token,','))
{
found = (token == board);
}
加载中,请稍侯......
精彩评论