user231032
user231032

Reputation:

Need help with a first name last name program

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

Answers (5)

gether roe
gether roe

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

Konstantin Spirin
Konstantin Spirin

Reputation: 21291

name.Split(' ').Reverse().Aggregate((acc, c) => acc + ", " + c);

Upvotes: 1

Adriaan Stander
Adriaan Stander

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

Cory Charlton
Cory Charlton

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

Michael Petrotta
Michael Petrotta

Reputation: 60902

Here's the approach I would take.

  1. Find the index of the space in the name.
  2. Extract the first name, by extracting all characters from the beginning of the string to just before the space you found.
  3. Extract the last name, by extracting all characters from just after the space to the end of the string.

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

Related Questions