Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string==string comparison failing?

Tags:

Following is the code snippet of what I did, can some body help me where I have wrongly coded it:

#include<iostream>
using namespace std;

void modifyName(string &name)
{
    size_t sep = string::npos;
    sep = name.find_first_of(".");

    if(sep != string::npos) { name[sep] = '\0'; }
}

int main()
{
    string name("test.rtl");
    string someName("test");
    modifyName(name);

    if( someName == name ) //Failing??
        cout<<"MATCHED"<<endl;
    return 0;
}
like image 378
pankiii Avatar asked Jun 10 '11 07:06

pankiii


2 Answers

As others have said, the strings don't match, as one is "test\0rtl" and the other is "test". It's fine to use == for std::string comparison, as the operator is overloaded for string equality. To do what you want, you should try replacing

if(sep != string::npos) { name[sep] = '\0'; }

with

if(sep != string::npos) { name.resize(sep); }
like image 172
Tom Avatar answered Sep 29 '22 18:09

Tom


It's failing, because they are not the same.. You haven't "cut" the string, just changed a char in it.

someName is test, while name is test\0rtl ( std::string allows you to have zero-chars('\0') inside )

To cut the string, you need to use std::string::resize or to self-assign the substring, using std::string::substr. I'd recommend resize.

like image 33
Kiril Kirov Avatar answered Sep 29 '22 19:09

Kiril Kirov