Habil Ganbarli
Habil Ganbarli

Reputation: 223

Splitting Full Name

I have string for instance, "John Daws Black" splitted with spaces and I need to split them to two parts so that there will be name part like "John Daws" and surname part like "Black". However the front name part can be any length like "John Erich Daws Black". My code can get the last part:

public String getSurname(String fullName){
    String part = "";
     for (String retval: fullName.split(" "))
         part = retval;
         return part;
}

But I don't know how to get the front part.

Upvotes: 8

Views: 30582

Answers (8)

Shaheen Ahamed S
Shaheen Ahamed S

Reputation: 176

Try this :

String[] name = fullname.split(" ")
if(name.size > 1){
    surName = name[name.length - 1]
    for (element=0; element<(name.length - 1); element++){
        if (element == (name.length - 1)) 
            firstName = firstName+name[element]
        else 
            firstName = firstName+name[element]+" "
    }
}
else 
    firstName = name[0]

Upvotes: 0

Edward J Beckett
Edward J Beckett

Reputation: 5140

Here's a solution I've used before that accounts for suffixes too.. ( 3 chars at the end )

/**
 * Get First and Last Name : Convenience Method to Extract the First and Last Name.
 *
 * @param fullName
 *
 * @return Map with the first and last names.
 */
public static Map<String, String> getFirstAndLastName(String fullName) {

    Map<String, String> firstAndLastName = new HashMap<>();

    if (StringUtils.isEmpty(fullName)) {
        throw new RuntimeException("Name Cannot Be Empty.");
    }

    String[] nameParts = fullName.trim().split(" ");

    /*
     * Remove Name Suffixes.
     */
    if (nameParts.length > 2 && nameParts[nameParts.length - 1].length() <= 3) {
        nameParts = Arrays.copyOf(nameParts, nameParts.length - 1);
    }

    if (nameParts.length == 2) {
        firstAndLastName.put("firstName", nameParts[0]);
        firstAndLastName.put("lastName", nameParts[1]);
    }

    if (nameParts.length > 2) {
        firstAndLastName.put("firstName", nameParts[0]);
        firstAndLastName.put("lastName", nameParts[nameParts.length - 1]);
    }

    return firstAndLastName;

}

Upvotes: 1

Salman
Salman

Reputation: 1264

Just a re-write for Andreas answer above but using sperate methods to get first and last name

    public static String get_first_name(String full_name)
    {
      int last_space_index = full_name.lastIndexOf(' ');
      if (last_space_index == -1) // single name
          return full_name;
      else
          return full_name.substring(0, last_space_index);
    }

    public static String get_last_name(String full_name)
    {
      int last_space_index = full_name.lastIndexOf(' ');
      if (last_space_index == -1) // single name
          return null;
      else
          return full_name.substring(last_space_index + 1);
    }

Upvotes: 1

user1270392
user1270392

Reputation: 3111

Below methods worked for me. It takes into account that if middle name is present, then that gets included in first name:

private static String getFirstName(String fullName) {
        int index = fullName.lastIndexOf(" ");
        if (index > -1) {
            return fullName.substring(0, index);
        }
        return fullName;
    }

    private static String getLastName(String fullName) {
        int index = fullName.lastIndexOf(" ");
        if (index > -1) {
            return fullName.substring(index + 1 , fullName.length());
        }
        return "";
    }

Upvotes: 3

dmitryvinn
dmitryvinn

Reputation: 412

//Split all data by any size whitespace 
final Pattern whiteSpacePattern = Pattern.compile("\\s+");
final List<String> splitData = whiteSpacePattern.splitAsStream(inputData)
.collect(Collectors.toList());

//Create output where first part is everything but the last element
if(splitData.size() > 1){
    final int lastElementIndex = splitData.size() - 1;
    //connect all names excluding the last one
    final String firstPart = IntStream.range(0,lastElementIndex).
    .mapToObj(splitData::get)
    .collect(Collectors.joining(" "));

    final String result = String.join(" ",firstPart,
    splitData.get(lastElementIndex));
}

Upvotes: 1

void
void

Reputation: 7880

Get the last element of the array after spliting it:

    String fullName= "John Daws Black";
    String surName=fullName.split(" ")[fullName.split(" ").length-1];
    System.out.println(surName);

Output:

Black

Edit: for the front part, use substring:

    String fullName= "John Daws Black";
    String surName=fullName.split(" ")[fullName.split(" ").length-1];
    String firstName = fullName.substring(0, fullName.length() - surName.length());
    System.out.println(firstName );

Output:

John Daws 

Upvotes: 1

user4910279
user4910279

Reputation:

Try this.

public String getName(String fullName){
    return fullName.split(" (?!.* )")[0];
}

public String getSurname(String fullName){
    return fullName.split(" (?!.* )")[1];
}

Upvotes: 3

Andreas
Andreas

Reputation: 159086

Just find the last space, then manually split there using substring().

String fullName = "John Erich Daws Black";
int idx = fullName.lastIndexOf(' ');
if (idx == -1)
    throw new IllegalArgumentException("Only a single name: " + fullName);
String firstName = fullName.substring(0, idx);
String lastName  = fullName.substring(idx + 1);

Upvotes: 27

Related Questions