0

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

Hello friends 123

Here i want to add "\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];
Mahesh Babariya
  • 4,560
  • 6
  • 39
  • 54
Mahesh
  • 355
  • 1
  • 5
  • 17

4 Answers4

6
      Try this
            String sentence  = "Hello friends 123456";
            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

 123456
Anoob C I
  • 171
  • 13
  • 2
    Also inserts a space at the end of the string. And it trims the end of the string (it'd replace multiple spaces at the end with a single space). And it creates lots of unnecessary strings. – Andy Turner Oct 25 '16 at 08:04
0

Try the below code...it will work

parts[parts.length]=parts[parts.length-1];
parts[parts.length-1]="\n";
raasesh
  • 161
  • 11
0

Please try this.

String sentence  = "I am Mahesh 123";
        String[] parts = sentence.split(" ");
        String string="";
        for (int i =0;i<parts.length;i++)
        {
            if (i==parts.length-1)
            {
                string = string+"\n"+parts[i];
            }
            else
            string = string+" "+parts[i];

        }
        Toast.makeText(Help.this, string, Toast.LENGTH_SHORT).show();
iasoftsolutions
  • 251
  • 2
  • 4
0

You want to add a break/new line at the end of your string. You can find the space via lastIndexOf(), this will give you the int of where the space is located in the String sentence. You can use this small example here:

public class Main {

    public static void main(String[] args) {
        String sentence =  "I am Mahesh 123";
        int locationOfLastSpace = sentence.lastIndexOf(' ');

        String result = sentence.substring(0, locationOfLastSpace) //before the last word
            + "\n" 
            + sentence.substring(locationOfLastSpace).trim(); //the last word, trim just removes the spaces

        System.out.println(result);
    }
}

Note that StringBuilder is not used because since Java 1.6 the compiler will create s StringBuilder for you

Community
  • 1
  • 1
Igoranze
  • 1,506
  • 13
  • 35