0

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.

I've defined the last name as LFM.substring(0, commaSpace) . commaSpace being the name for the ", " in the input of the LFM (Last, First Middle) user input.

Then I needed to define 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) ); ? That way I can just print 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);

1 Answer 1

1

Use replaceAll or replaceFirst functions since it accepts regex as first argument.

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

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

more appropriate replace \\w+ with [a-zA-Z]+ in the above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.