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.
String.split
Regular ExpressionYou 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
Alternatively, you could trim
str[1]
before getting the first character like
sb.append(str[1].trim().charAt(0)); //<-- will also remove leading space
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With