How to trim multiple lines in a string Android?

Viewed 362

Hi we need a formatted string for our application.

Expected output :

Blow the candles real hard,
Coz now you have aged,
Don't pretend so much my dear,
Don't behave so sage,
Happy birthday to you,
Have a nice day,
Make the most of your day!

I want to format a string as shown above, when I use trim() function for string it gives the result as

Blow the candles real hard,
 Coz now you have aged,
Don't pretend so much my dear,
 Don't behave so sage,
 Happy birthday to you,
 Have a nice day,
Make the most of your day!  

I want to remove the white spaces at the start of each line. I have used these functions below, it trimmed the start and end of the string but not lines.

   poemText = poemText.trimMargin()
   poemText = poemText.trimIndent()
   poemText = poemText.replace("\n ", "\n")
   for(line in poemText.lines())
   {line.trim()}

Any help is appreciated

4 Answers

You can use replace with regex like this:

poemText = poemText.replace("""^\s*|\s*$""".toRegex(), "")
                   .replace("""\s*(\r|\n|\r\n)\s*""".toRegex(), "\n")  

Code example

The first replace will remove all the spaces in the beginning and in the end of of text, and the second one will remove the spaces in the end and in the beginning of each line.

You can use ^\h+ to match 1 or more horizontal whitespace chars from the start of the string and use (?m) to enable multiline.

In the replacement use an empty string.

     val poemText = """
Blow the candles real hard,
 Coz now you have aged,
Don't pretend so much my dear,
 Don't behave so sage,
 Happy birthday to you,
 Have a nice day,
Make the most of your day!"""
    
    println(
        """(?m)^\h+"""
        .toRegex()
        .replace(poemText, "")
    )

Output

Blow the candles real hard,
Coz now you have aged,
Don't pretend so much my dear,
Don't behave so sage,
Happy birthday to you,
Have a nice day,
Make the most of your day!

See a Kotlin demo

Does this help?

poemText = poemText.trim().replaceAll("\n ", "\n")

Because you have white spaces between sentences so first trim() to get rid of the start and the end of the String and then replace the comma and the white spaces in between with\n

I think you can turn java into kotlin

 String text = "Blow the candles real hard,\n " +
            "    Coz now you have aged,\n " +
            "    Don't pretend so much my dear,\n " +
            "    Don't behave so sage,\n " +
            "    Happy birthday to you,\n " +
            "    Have a nice day,\n " +
            "    Make the most of your day!";

    String[] lines = null;
    lines = text.split("\n");

    String newText = "";
    for(int i = 0 ; i<lines.length ; i++){
        newText = (newText + lines[i]).trim()+"\n";
    }

    Log.e("newText",newText);
Related