任何人都可以建议我在C ++中分割名称的简单方法

时间:2011-01-09 01:07:58

标签: c++

我一直试图将名字拆分为名字和姓氏,但我确信我的实施并不是最简单的。

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;

提前致谢

5 个答案:

答案 0 :(得分:5)

如何使用字符串中的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;

我还使用std::string::npos来表示字符串的最后位置。从技术上讲,我可以通过name.substr(pos)离开,因为npos是默认参数。

另外,请参阅this有关字符串拆分的帖子。你会在那里找到更好的物品,比如提到Boost分裂功能。

答案 1 :(得分:1)

如果前导,尾随和中间空格(和/或标签)的数量不确定,那么以下是我可以建议的非常干净(但不一定是最有效)的替代方案:

std::istringstream ssname( name ); // needs <sstream> header
string first, last;
ssname >> first >> last;

答案 2 :(得分:0)

可以尝试

strtok

分割字符串的功能,代码将是干净的

答案 3 :(得分:0)

@Akhil ::我不建议在c ++程序中使用strtok,因为它不能用于运行strtok的多个实例,因为它在其实现中使用静态变量。如果您打算在任何时间点使用单个实例,那么您可以使用它。但更好的是使用c ++设计模式,而不是使用c ++:)

答案 4 :(得分:0)

狡猾地扩展这个想法:

#include <map>
#include <memory>
#include <functional>
#include <algorithm>
#include <iostream>
#include <sstream>


int main()
{
    std::string             name    = "   Martin Paul Jones   ";
    std::string::size_type  s       = name.find_first_not_of(" \t\n\r");
    std::string::size_type  e       = name.find_last_not_of(" \t\n\r");
    std::string             trim    = name.substr(s, (e - s + 1));
    std::string             first   = trim.substr(0, trim.find_first_of(" \t\n\r"));
    std::string             last    = trim.substr(trim.find_last_of(" \t\n\r") + 1);

    std::cout << "N(" << name << ") " << " T(" << trim << ") First(" << first << ") Last(" << last << ")\n";

    // Alternative using streams
    std::stringstream       namestream(name);
    namestream >> first >> last;
    while(namestream >> last) { /* Empty */ } // Skip middle names
    std::cout << "N(" << name << ")  First(" << first << ") Last(" << last << ")\n";
}

尝试:

> g++ xx.cpp
> ./a.out
N(   Martin Paul Jones   )  T(Martin Paul Jones) First(Martin) Last(Jones)
N(   Martin Paul Jones   )  First(Martin) Last(Jones)