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

<p>



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


</p>

<p>Fixed that for you. Because my last name has a space in it, and I’m sick of seeing “Hey Mr. firstName first-half-of-last-name!”</p>

<p>Wow…</p>

<p>You guys stole my thunder :frowning: I was just about to boot up Textpad and program this problem for the OP.</p>

<p>^same, life’s harsh bro</p>

<p>Hey, I’m sure I could find you a comp sci assignment I don’t feel like doing…</p>

<p>Yeah. There are many shorter ways to do it.</p>

<p>I did it the long why because I forgot split existed.</p>

<p>MIT</p>

<p>Why did you use a for loop? I am kinda lost as to why you used that. I would of been easier to just read the words off the command line, assign them to a variable, then print.</p>

<p>Because I was told that the name already had a value… so I traverse through the characters of the string.</p>

<p>aeroengineer wins</p>

<p>


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


Readability is very important.</p>

<p>Hence why one should go with the split method.</p>

<p>And I just realized I put those in backwards in the indexOf way… /embarrassed</p>

<p>But fine…</p>

<p>



public static String convertName(String name) 
{
     String first = name.substring( 0, name.indexOf(" ") );    //Everything up to the first space
     String last  = name.substring( name.indexOf(" ") + 1 );   //Everything after the first space (excluding the space itself)
     return last + ", " + first;
}</p>

<p>

</p>