简体   繁体   中英

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.

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

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.

name.Split(' ').Reverse().Aggregate((acc, c) => acc + ", " + c);
        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 ;-)
#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM