简体   繁体   English

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

[英]How do I define the end of a string in Java?

I have a string that a user inputs their name in [Last, First Middle] format and I need to change it to [First Middle Last] format. 我有一个字符串,用户以[Last,First Middle]格式输入其名称,我需要将其更改为[First Middle Last]格式。

I've defined the last name as LFM.substring(0, commaSpace) . 我已经定义了last名字LFM.substring(0, commaSpace) commaSpace being the name for the ", " in the input of the LFM (Last, First Middle) user input. commaSpaceLFM (最后一个,第一中)用户输入的输入中“,”的名称。

Then I needed to define firstMiddle . 然后我需要定义firstMiddle My question to you is, how could I define the end of the string LFM so I can have firstMiddle be LFM.substring(commaSpace, (end of string) ); 我对您的问题是,如何定义字符串LFM的结尾,以便让firstMiddleLFM.substring(commaSpace, (string of end) ); LFM.substring(commaSpace, ? That way I can just print firstMiddle + last . 这样,我可以只打印firstMiddle + last

ALL OF MY CURRENT CODE: 我所有的当前代码:

(IT'S REALLY MESSY, SORRY) (真的很混乱,抱歉)

    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);

Use replaceAll or replaceFirst functions since it accepts regex as first argument. 使用replaceAllreplaceFirst函数,因为它接受正则表达式作为第一个参数。

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

DEMO 演示

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM