get First Name And Last Name Array From Full Name - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

get First Name And Last Name Array From Full Name

Demo Code

public class Main {

  public static String[] getFirstNameAndLastNameArrayFromFullName(String fullName) {
    String[] firstnameAndLastnameArr = fullName.split(" ");
    if (firstnameAndLastnameArr.length == 2) {
      return firstnameAndLastnameArr;
    } else if (firstnameAndLastnameArr.length == 1) {
      String firstName = firstnameAndLastnameArr[0];
      firstnameAndLastnameArr = new String[2];
      firstnameAndLastnameArr[0] = firstName;
      firstnameAndLastnameArr[1] = "";
      return firstnameAndLastnameArr;
    } else if (firstnameAndLastnameArr.length > 2) {
      String firstName = firstnameAndLastnameArr[0];
      String lastName = firstnameAndLastnameArr[2];

      firstnameAndLastnameArr = new String[2];
      firstnameAndLastnameArr[0] = firstName;
      firstnameAndLastnameArr[1] = lastName;
      return firstnameAndLastnameArr;
    } else {//from w  w w  . ja  va2s.co m
      firstnameAndLastnameArr = new String[2];
      firstnameAndLastnameArr[0] = "";
      firstnameAndLastnameArr[1] = "";
      return firstnameAndLastnameArr;
    }
  }
}

Related Tutorials