MaheshB psk MaheshB psk - 1 month ago 6
Java Question

How to prepend "\n" to the last word of String?

I want to prepend "\n" to the last word of the string
for example

Hello frinens 123


Here i want to ad "\n" just before the word "123"

I tried below code but having no idea what to do now

String sentence = "I am Mahesh 123"
String[] parts = sentence.split(" ");
String lastWord = "\n" + parts[parts.length - 1];

Answer
      Try this
            String sentence  = "Hello friends 123";
            String[] parts = sentence.split(" ");
            parts[parts.length - 1] = "\n" + parts[parts.length - 1];

            StringBuilder builder = new StringBuilder();
            for (String part : parts) {
                builder.append(part);
                builder.append(" ");
            }

            System.out.println(builder.toString());

Output will be :~

Hello friends

123