pan*_*iii 19 c++ string comparison
以下是我所做的代码片段,有些身体可以帮助我,我错误地编码了它:
#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;
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*Tom 21
正如其他人所说,字符串不匹配,就像一个是"test\0rtl"另一个"test".可以用来==进行std::string比较,因为运算符因字符串相等而过载.要做你想做的事,你应该尝试更换
if(sep != string::npos) { name[sep] = '\0'; }
Run Code Online (Sandbox Code Playgroud)
同
if(sep != string::npos) { name.resize(sep); }
Run Code Online (Sandbox Code Playgroud)
Kir*_*rov 13
它失败了,因为它们不一样.你没有"剪切"字符串,只是更改了字符串.
someNameis test,while nameis test\0rtl(std::string允许你在'\0'里面有零chars())
要剪切字符串,您需要使用std::string::resize或自行分配子字符串std::string::substr.我推荐resize.
在这一行
if(sep != string::npos) { name[sep] = '\0'; }
Run Code Online (Sandbox Code Playgroud)
您正在修改字符串"test\0rtl".std :: basic_string可以包含空字符,因此字符串不相同.你可以substr用来截断字符串:
if(sep != string::npos) { name = name.substr(sep); }
Run Code Online (Sandbox Code Playgroud)
这将导致字符串变为"test",应该(!!)正确比较.