In C++/Cpp, Split Full Name Into First, Middle And Last Name.

#include<iostream>
#include<string>
using namespace std;

void lastFirstMiddle(string full, string &first, string &middle, string &last){
	size_t pos = full.find(',');
	last = full.substr(0, pos);
	full = full.substr(pos+2);
	pos = full.find(' ');
	first = full.substr(0, pos);
	middle = full.substr(pos+1);
}

void firstMiddleLast(string full, string &first, string &middle, string &last){
	size_t pos = full.find(' ');
	first = full.substr(0, pos);
	full = full.substr(pos+1);
	pos = full.find(' ');
	middle = full.substr(0, pos);
	last = full.substr(pos+1);
}

int main(){
	string full, first, middle, last;
	while(1){
		cout << "Enter a full name: ";
		if(!(getline(cin,full))){
			break;
		}
		if(string::npos == full.find(',')){
			firstMiddleLast(full, first, middle, last);
		} else {
			lastFirstMiddle(full, first, middle, last);
		}
		cout << "    " << "First name: " << first << endl;
		cout << "    " << "Middle name: " << middle << endl;
		cout << "    " << "Last name: " << last << endl;
	}
	return 0;
}
Download

Comments

Popular posts from this blog