Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace every line by \n

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
like image 432
khaled Avatar asked Nov 24 '25 09:11

khaled


2 Answers

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().

like image 138
Belal Khan Avatar answered Nov 25 '25 23:11

Belal Khan


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.

like image 27
Akanshi Srivastava Avatar answered Nov 25 '25 21:11

Akanshi Srivastava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!