Reputation:
I need help to create a program that allows the user to input their firstname and lastname separated by a space. I then need to display this information in reverse for example.
Input:
John Doe
Display:
Doe, John
Can someone please help me with this, I have been trying to do this for over a week and have made no head way. I am programming it in Visual Studio 2008 C#. Thanks in advance for any and all help.
Upvotes: 1
Views: 4206
Reputation: 1
#include<iostream>
using namespace std;
int main()
{
//variables for the names
char first[31], last[31];
//prompt user for input
cout<< "Give me your name (first then last) and I will reverse it: ";
cin>> first;
cin>> last;
cout<< "Your name reversed is " << last << ", " << first << endl;
return 0;
}
Upvotes: 0
Reputation: 21291
name.Split(' ').Reverse().Aggregate((acc, c) => acc + ", " + c);
Upvotes: 1
Reputation: 166406
Try using the String.Split Method for string, with the required seperator.
Once you have the string array, you can use these to format a return value. (see String.Format Method (String, Object[])
Please also remember that your string array might not contain the correct number of entries you expect so you might want to check out Array.Length Property (myStringArray.Length).
Upvotes: 3
Reputation: 8938
string fullName = "John Doe";
string[] nameParts = fullName.Split(' ');
string firstName = nameParts[0];
string lastName = string.Empty;
if (nameParts.Length == 2)
{
lastName = nameParts[1];
}
else
{
for (int i = 1; i < nameParts.Length; i++)
{
lastName += nameParts[i];
}
}
string reversedName = lastName + ", " + firstName; // Cory Charlton rocks ;-)
Upvotes: 0
Reputation: 60902
Here's the approach I would take.
This should be enough to get you started. The methods you need will be in the String
class. If you get stuck on any of these steps, post what you've tried and where it fails.
Upvotes: 1