Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take a String of LastName, FirstName and return FirstInitial.LastName

Tags:

java

Expected Input: Doe, John

Expected Output: J. Doe

     public static void main(String[] args) {

         String z = "Doe, John";
         System.out.println(z);
         String y = formatName(name);
         System.out.println(y);
     }

     public static String formatName(String name) {
        String str[] = name.split(",");
        StringBuilder sb = new StringBuilder();
        sb.append(str[1].charAt(0));
        sb.append(". ");
        sb.append(str[0]);
        return sb.toString();
   }

My output is not as expected.

like image 546
Progamminnoob Avatar asked Feb 07 '23 11:02

Progamminnoob


2 Answers

Match (Optional) White Space with String.split Regular Expression

You have a space after the comma in your input, you could modify your regular expression in split from

String str[] = name.split(",");

to

String str[] = name.split(",\\s*");

to match and remove optional white-space. After I made the above change I ran your code, and got the (expected) output

Doe, John
J. Doe

Trim the Leading White Space

Alternatively, you could trim str[1] before getting the first character like

sb.append(str[1].trim().charAt(0)); //<-- will also remove leading space

Regular Expression With a Compiled Pattern

Another possible option is compiling a regex Pattern and using a Matcher like

// Match (and group) one more characters followed by a "," and
// optional whitespace. Then match (and group) one character followed
// any number of optional characters.
private static Pattern pattern = Pattern.compile("(.+),\\s*(.).*");
public static String formatName(String name) {
    Matcher m = pattern.matcher(name);
    if (m.matches()) {
        return String.format("%s. %s", m.group(2), m.group(1));
    }
    return name;
}
like image 180
Elliott Frisch Avatar answered Feb 15 '23 11:02

Elliott Frisch


Another simple way to get FirstInitial.LastName

Other than using split, you can use substring and based on the position of the comma ,, manipulate the name to get the output:

String s = "Doe, John";

s = s.replace(" ", "");                                      //remove spaces
int i = s.indexOf(",");                                      //get pos of comma
String name = s.charAt(i+1) + ". " + s.substring(0, i);      //create name

Output:

J. Doe
like image 44
user3437460 Avatar answered Feb 15 '23 09:02

user3437460