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;
}
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); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With