Answer to Question #277457 in C++ for Gus

Question #277457

Write a program that converts each name to the following form: firstName middleName lastName. Your program must read each student’s entire name in a variable and must consist of a function that takes as input a string, consists of a student’s name, and returns the string consisting of the altered name to print to the terminal. Use the string function find to find the index of ,; the function length to find the length of the string; and the function substr to extract the firstName, middleName, and lastName.


1
Expert's answer
2021-12-09T02:23:18-0500
#include<iostream>
#include<string>
using namespace std;

string alteredName(string in)
{
	string input =in;
	int i=0;
	//clear spaces from begin
	while(input[i++]==' ');
	i--;
	input=input.substr(i);
	//find lastName
	int pos=input.find(",");
	string lastName=input.substr(0,pos);
	i=0;
	//clear spaces from end of lastName
	while(lastName[i++]!=' ');
	i--;
	lastName=lastName.substr(0,i);
	
	//update input
	input=input.substr(pos+1);
	i=0;
	//clear spaces
	while(input[i++]==' ');
	i--;
	input=input.substr(i);
	//find firstName
	pos=input.find(",");
	string firstName=input.substr(0,pos);

	//update input
	input=input.substr(pos+1);
	i=0;
	//clear spaces
	while(input[i++]==' ');
	i--;
	input=input.substr(i);
	//find middleName
	pos=input.find(",");
	string middleName=input.substr(0,pos);
	return firstName+" "+middleName+" "+lastName;
}


int main()
{
	string arr[]={ {" Roosevelt, Franklin, Delano"},
				   {"Trumann, Harry, S." },
				   {" Churchill, Winston, Leonard"} };
	cout<<"Primary array: \n";		   
	for(int i=0;i<3;i++)
	{
		cout<<arr[i]<<endl;	
	}
	cout<<"\nResult is: \n";		   
	for(int i=0;i<3;i++)
	{
		cout<<alteredName(arr[i])<<endl;	
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog