How to take the string LastName, FirstName and return FirstInitial.LastName

Expected Entry : 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 conclusion is not as expected.

+4
source share
4 answers

Matching (optional) White space with String.splitregular expression

Do you have a space after the comma on your input, you can change your regular expression splitfrom

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

to

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

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

Doe, John
J. Doe

Trim the leading white space

, trim str[1] , ,

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

Pattern

- regex Pattern Matcher,

// 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;
}
+4

FirstInitial.LastName

split, ,, , :

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

:

J. Doe
+2

sb.append(str[1].charAt(0));, charAt() 1 0.

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

split(", ")

+1

, .

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();
    }
+1

All Articles