简体   繁体   中英

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

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.

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;
}

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

sb.append(str[1].charAt(0)); , index for charAt() should be 1 not 0 .

String str[] = name.split(","); will return [Doe, John] , notice the space before second element.

better yet use split(", ")

I tried this based on what i understood. Use for loop and trim the items

public static String formatName(String name) {
        String str[] = name.split(",");
        for(int i = 0 ; i < str.length ; i++){
            str[i] = str[i].trim();
            //System.out.println("+"+str[i]+"+");
        }

        StringBuilder sb = new StringBuilder();
        sb.append(str[1].charAt(0));
        sb.append(".");
        sb.append(str[0]);
        sb.append(".");
        return sb.toString().trim();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM