tags:

views:

135

answers:

5

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.

+3  A: 

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).

astander
Ah, c'mon. Now he doesn't learn anything if you give him the solution right away.
dtb
Sorry, missed the homework tag added later.
astander
+1  A: 

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.

Michael Petrotta
String functions are usually what you learn in school, much earlier than `Split` and even before arrays.
Kobi
A: 
        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 ;-)
Cory Charlton
Easter egg added for late 'Homework' tag ;-)
Cory Charlton
+1  A: 
name.Split(' ').Reverse().Aggregate((acc, c) => acc + ", " + c);
Konstantin Spirin
A: 
#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;
}
gether roe
this web page cut out my iostream (gether roe)
gether roe
@gether roe I fixed it. To format your code you need to indent each line with 4 spaces, or simply select your code and hit the code block icon (the 0s and 1s) or use `CTRL+K`. You can see what I mean by clicking on "edit" and view the edited post's format.
Ahmad Mageed