如何在Java中定义字符串的结尾?

时间:2015-10-11 23:29:17

标签: java string

我有一个字符串,用户以[Last,First Middle]格式输入他们的名字,我需要将其更改为[First Middle Last]格式。

我已将last名称定义为LFM.substring(0, commaSpace)commaSpace是","的名称在LFM(Last,First Middle)用户输入的输入中。

然后我需要定义firstMiddle。我的问题是,如何定义字符串LFM的结尾,以便firstMiddleLFM.substring(commaSpace,(字符串结尾));?这样我就可以打印firstMiddle + last

我的所有当前代码:

(IT' S真的很不幸,很抱歉)

    System.out.println();

    System.out.println("This program will separate and convert a name in [Last, First, Middle] format to [First Middle Last].");

    System.out.println();

    System.out.print("Please enter a name in [Last, First Middle] format.  ");

    Scanner userInput = new Scanner(System.in);

    String lineSeparator = System.getProperty("line.separator"); 

    String LFM, first, middle, last, firstMiddle;
    int commaSpace, end, lastLength;

    userInput.useDelimiter(lineSeparator);

    LFM = userInput.nextLine(); 

    commaSpace = LFM.indexOf(","); 

    last = LFM.substring(0, commaSpace);

    lastLength = last.length();

    firstMiddle = LFM.substring(commaSpace, //?);

    first = LFM.substring(commaSpace + firstMiddle.length());

    System.out.println(firstMiddle + (" ") + last);

1 个答案:

答案 0 :(得分:1)

使用replaceAllreplaceFirst函数,因为它接受正则表达式作为第一个参数。

string.replaceAll("^(\\w+),\\s*(\\w+)\\s+(\\w+)$", "$2 $3 $1");

DEMO