简体   繁体   English

如何获取LastName,FirstName的字符串并返回FirstInitial.LastName

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

Expected Input : Doe, John 预期的输入 :Doe,John

Expected Output : J. Doe 预期产出 :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 使用String.split正则表达式匹配(可选)空格

You have a space after the comma in your input, you could modify your regular expression in split from 输入中的逗号后面有空格,您可以在split修改正则表达式

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 或者 ,您可以在获得第一个字符之前trim str[1]

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

Regular Expression With a Compiled Pattern 使用编译Pattern正则表达式

Another possible option is compiling a regex Pattern and using a Matcher like 另一种可能的选择是编译正则表达式 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;
}

Another simple way to get FirstInitial.LastName 另一种获取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 . charAt()索引应为1而不是0。

String str[] = name.split(","); will return [Doe, John] , notice the space before second element. 将返回[Doe, John] ,注意第二个元素之前的空格。

better yet use split(", ") 更好的是使用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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据名字和姓氏生成唯一的 ID? - How to generate unique Id based on the FirstName and LastName? 如何使用 sAMaccountName 在活动目录中搜索用户,其中 sAMaccountName 是 (firstinitial+lastName)+(regex) 以任何数字结尾的连接? - How to search user in active directory with sAMaccountName, where sAMaccountName is a concat of (firstinitial+lastName)+(regex)ending with any digits? Java Regex为Java中的姓,名 - Java Regex for lastname, firstname in java 清除缓冲区,输出firstname,lastname - Clearing the buffer, output firstname,lastname CN&#39;LastName,FirstName&#39;的JNDI InvalidnameException - JNDI InvalidnameException for CN 'LastName, FirstName' Spring Security自定义身份验证如何访问名字和姓氏 - Spring security custom authentication how to access firstname and lastname 将一个bean中的firstName,lastName映射为另一个bean中的名字 - Map firstName, lastName in one bean to name in another 在java中将全名拆分为Salutation,Firstname和lastname - To split fullname into Salutation,Firstname and lastname in java 是否可以将全名转换为名字和姓氏? - Is it possible to convert full name to firstname and lastname? 正则表达式查找“​​姓氏,名字中间名”格式 - Regular Expression to find "lastname, firstname middlename" format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM