两个名字的首字母加上完整的姓氏

时间:2015-10-09 17:55:19

标签: java names

我正在努力解决这个问题。这个回归是例如:" JS John Smith"但是当我试图把两个名字加上姓氏时,我得到的就是一团糟。我希望在我打字时得到:" John William Smith"这样的事情:" JW史密斯",有人知道这么热吗?

import java.io.*;
import java.io.BufferedReader;

public class ex54 {

    public static void main(String[] args) {
        System.out.print("Enter your name: ");
        BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
        String fullName = null;
        try{
            fullName = br.readLine();
        } catch (IOException ioe) {
            System.out.println("Error");
            System.exit(1);
        }
        int spacePos = fullName.indexOf(" ");
        // String firstName = fullName.substring(0, spacePos);
        // String secondName = fullName.substring(1, spacePos);
        String firstInitial = fullName.substring(0, 1);
        String secondInitial = fullName.substring(spacePos+1, spacePos+2);
        String userName = (firstInitial + secondInitial + " ").concat(fullName);

        System.out.println("Hello, your user name is: " + userName);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以拆分名称,假设您有三个名字的字符串:

String[] names = fullname.split(" ");
System.out.println("" + names[0].charAt(0) + names[1].charAt(0) + " " + names[2]);

答案 1 :(得分:0)

    int spacePos = -1;

    System.out.print("Hello, your user name is:");
    do {
        System.out.print(" "+fullName.substring(spacePos+1, spacePos+2));
        fullName = fullName.substring(spacePos+1);
        spacePos = fullName.indexOf(" ");
    }while(spacePos != -1);
    System.out.println("\b"+fullName);

答案 2 :(得分:0)

只是为了踢,这是一个使用正则表达式的实现:

private static String firstNamesToInitials(String name) {
    StringBuilder buf = new StringBuilder();
    Matcher m = Pattern.compile("\\b([A-Z])[A-Za-z]*\\b").matcher(name);
    String lastName = null;
    while (m.find()) {
        buf.append(m.group(1));
        lastName = m.group();
    }
    if (buf.length() <= 1)
        return lastName;
    buf.setCharAt(buf.length() - 1, ' ');
    return buf.append(lastName).toString();
}

测试

System.out.println(firstNamesToInitials("Cher"));
System.out.println(firstNamesToInitials("John Smith"));
System.out.println(firstNamesToInitials("John William Smith"));
System.out.println(firstNamesToInitials("Charles Philip Arthur George"));
System.out.println(firstNamesToInitials("Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"));

输出

Cher
J Smith
JW Smith
CPA George
PDFPJNRCTR Picasso