How would you flip a first and last name in Java?

<p>String name = <em>whatever the user inputs, such as “John Doe”</em></p>

<p>The output needs to be Doe, John. Or, lastName, firstName.</p>

<p>How would you do this?</p>

<p>Is their white space?</p>

<p>String first = in.next();
String last = in.next();
System.out.print(last + ", " + first);</p>

<p>Right?</p>

<p>^ That makes more sense. Because if you’re doing it on one input line…
reversing with whitespace is a *****.</p>

<p>Without the use of StringBuffers.</p>

<p>@FunStuff, I would assume that that is how you would do it, but there is only one string called “name.” So, yes, MIThopeful, name = firstName <em>space</em> lastName and I have to convert it to lastName, firstName.</p>

<p>Can’t alter the code, and make two strings?</p>

<p>Or use a 2-element String Array?</p>

<p>So you can’t create new Strings, and you have to do it on one line which starts with String name = ? You, sir, have gone beyond my very shallow knowledge of Java.</p>

<p>Use the split function.</p>

<p>This is exactly what we’re given:</p>

<p>This method returns a String with a name (first name last name - assume there is a space between the first name and last name) and converts it into the form “lastname, firstname”. </p>

<p>public static String convertName(String name)
{
//fill in code here
}</p>

<p>public static void main(String args)?</p>

<p>ffffffuuuuuu</p>

<p>Name is already given.
Correct?</p>

<p>LOL FunStuff.</p>

<p>Yes, the name is Grace Hopper.</p>

<p>Alright… I have one mildly complex solution…</p>

<p>



public static String convertName(String name) 
{
    String lastname = "";
    String firstname = "";
    for(int i = 0; i < name.length(); i++)
    {
        if(name.charAt(i) == ' ')
        {
            lastname = name.substring(i + 1);
            firstname = name.substring(0, i);</p>

<pre><code>    }
}
return lastname + ", " + firstname;
</code></pre>

<p>}


</p>

<p>^ BAMF, you are one.</p>

<p>Wow, MIT, awesome solution! That actually makes a lot of sense, thank you very much!</p>

<p>No problem.</p>

<p>MIThopeful16 is spot on. But if his solution doesn’t work try changing his if statement in the for loop to this:</p>

<p>if(name.charAt(i).equals(’ '))</p>

<p>-_-



public static String convertName(String name) 
{
        String[] names = name.split(" ");
    return names[1] + ", " + names[0];
}

or



public static String convertName(String name) 
{
     return name.substring(0, name.indexOf(" ") + 1) + ", " + name.substring(name.indexOf(" "));
}

</p>

<p>^elegant code right there</p>

<p>I forgot about the split method entirely.</p>