我刚开始学习Java而且我在格式化字符串时遇到了问题。在问题中,我有一个用户输入的字符串,其格式为“First Middle Last”。我需要输出以下格式的字符串:“Last,First MI。”(MI是初中)。
这是我到目前为止所做的,我的名字有效,但不确定如何从字符串中获取最后和中间的首字母。
// Variable declarations
String name, first, last, middle;
Scanner scan = new Scanner (System.in);
// Get name from user in format "First Middle Last"
System.out.println("Enter the person's name: ");
name = scan.nextLine();
// Get first, middle initial, and last name from the string
first = name.substring(0, name.indexOf(" "));
middle =
last =
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middle + ".");
因此,例如,如果用户输入:“John Robert Doe”,则输出为“Doe,John R。”
感谢任何帮助。
答案 0 :(得分:3)
您可以使用String类的split方法
// Get first, middle initial, and last name from the string
String nameParts [] = name.split(" ");
// not sure if you need these variables, but I guess you get the picture
first = nameParts [0];
middle = nameParts [1];
last = nameParts [2];
middleInital = middle.charAt(0);
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middleInital + ".");
答案 1 :(得分:1)
查看String.split
方法。这允许您查找子字符串。然后你只需要按正确的顺序放置它们
答案 2 :(得分:0)
查看String类的String split和charAt方法。
String person_data = "John Robert Doe" ;
String[] data = person_data.split(" ");
char MI = data[1].charAt(0);
System.out.println(data[2] +","+ data[0] + " "+ MI);
输出= Doe,John R
这里
Data[0] == "John"
Data[1] == "Robert"
Data[2] == "Doe"
MI = first character of Data[1] which is R.
答案 3 :(得分:0)
试试这个:
String name = "First Middle Last";
String[] data = name.split(" ");
String formatted = String.format("%s, %s %c.", data[2], data[0], data[1].charAt(0));
最后一行指定值“Last,First M.”如预期的那样变量formatted
。此解决方案使用Java的Formatter类,这对您的所有字符串格式化需求都有很大的帮助。
答案 4 :(得分:0)
您需要首先拆分字符串(使用String.split
)然后格式化。
原谅我,因为我在iPad上打字,答案如下:
String names = name.split("\\s+"); \\Split on whitespaces, including tab, newline and carriage return.
StringBuilder sb = new StringBuilder();
for (int x = 0; x < names.length; x++) {
switch (x) {
case 0: sb.apppend(names[names.length - 1]).append(", ");
break;
case 1: sb.append(names[0]).append(" ");
break;
case 2: sb.append(Character.toUpperCase(names[1].charAt(0))).append(".");
break;
default: break;
}
}
String fullName = sb.toString();