我一直试图将名字分为名字和姓氏,但我确信我的实施并不是最简单的.
string name = "John Smith";
string first;
string last (name, name.find(" "));//getting lastname
for(int i=0; i<name.find(" "); i++)
{
first += name[i];//getting firstname
}
cout << "First: "<< first << " Last: " << last << endl;
Run Code Online (Sandbox Code Playgroud)
提前致谢
如何使用字符串中的substr方法将事物与find结合起来:
std::string name = "John Smith"
std::size_t pos = name.find(" ");
std::cout << "First: " << name.substr(0, pos) << " Last: " << name.substr(pos, std::string::npos) << std::endl;
Run Code Online (Sandbox Code Playgroud)
我还用它std::string::npos来表示字符串的最后位置.Techincally,我可以name.substr(pos)像npos默认参数一样逃脱.
另外,请参阅此 SO帖子关于字符串拆分.你会在那里找到更好的物品,比如提到Boost分割功能.