2011-01-09 57 views
2

我一直在嘗試將名稱拆分成名字和姓氏,但我相信我的實現並不是最簡單的方法。任何人都可以建議我一個簡單的方法在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; 

在此先感謝

+8

我知道你可能會寫這一個簡單的使用,但你應該知道,分裂名稱可以是冒險的;有兩個字的姓,首先是姓,等等。 – Cascabel 2011-01-09 01:16:38

回答

5

如何使用從字符串substr方法分裂的事情了查找相結合:

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關於字符串拆分的SO帖子。你會在那裏找到更好的項目,就像提到Boost split函數一樣。

+0

很好的解決方案。但是,如果不使用「using namespace std;」,你還應該用「std ::」thingy加前綴「string」和「cout」,否? – liorda 2011-01-09 01:20:03

+0

@liorda好點! – wheaties 2011-01-09 01:20:43

1

如果有不明數量的前置,並在兩者之間的空間(和/或標籤),再下面是一個非常乾淨的(但不一定是最有效的)的替代方案,我可以建議:

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

可以嘗試

strtok 

功能分割字符串,代碼會乾淨

0

@ AKHIL ::我不建議使用的strtok在C++程序,因爲它可以不是b e用於運行strtok的多個實例,因爲它在其實現中使用了一個靜態變量。那麼你可以ofcourse使用它,如果你打算使用一個單一實例在time..but更好的任何一點去用C++設計模式wheb您使用C++ :)

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) 
相關問題