Question

I have to split a string containing a full name and need to create new first name and last name strings. I used this to split the full name based on the space between names:

  String fullName = "John Doe";
       String[] result = fullName.split(" ");
       for(String token:result)
            System.out.println(token);

I get the correct output, "John" and "Doe". How do I now use that to create

String firstName = "John";
String lastName = "Doe";

Thanks

Was it helpful?

Solution

String fullName = "John Doe";
String[] result = fullName.split(" ");
String firstName=result[0];
String lastName=result[1];

OTHER TIPS

    String fullName = "John Doe";
    String firstName=fullName.substring(0,fullName.indexOf(" "));
    String lastName=fullName.substring(fullName.lastIndexOf(" ")+1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top