How to replace every line by \n

747

Solution 1

You can try this it will work.

public class HelloWorld{

     public static void main(String []args){
        String s = "Hello\nHello";
        System.out.println(s.replaceAll("\n","\\\\n"));
     }

}

It is a plain java code but you can use the same function replaceAll in android as well and instead of S.O.P use setText().

Solution 2

Save the input in a string. Now check each character and store it in another string but when you encounter a next line or "\n" then append the string with "\"+"n". Keep checking till you encounter the end of string or null. You can also run a loop till sizeof(string). This new string will be your expected output.

Share:
747
khaled
Author by

khaled

Updated on December 11, 2022

Comments

  • khaled
    khaled over 1 year

    I have a TextField and bellow of the TextField there is a Card and Text as child,The child of the Card display the String that entered in TextField, I want to replace every line by \n, How can I do this?

    Example:

    Text entered :

    Hello
    
    World
    

    result :

    Hello
    
    World
    

    expected :

    Hello\nWorld
    
  • khaled
    khaled almost 5 years
    Thanks it worked but instead of "\\\\n" I used "\\n"
  • Julio Henrique Bitencourt
    Julio Henrique Bitencourt almost 5 years
    I want to know why the question is tagged as 'Dart' and 'Flutter', and the accepted answer is in Java... ?
  • khaled
    khaled almost 5 years
    @JulioHenriqueBitencourt This answer solved my problem and all I want from this answer is .replaceAll("\n","\\\\n") which is common between Dart and Java