[英]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. 我的输出不如预期。
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
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
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.