简体   繁体   中英

How do i replace a double line with a single line in a string in Android?

I have a string:

 This is a test sentence 1.
 This is a test sentence 2.
 This is a test sentence 3.

 This is a test sentence 4.

 This is a test sentence 5.

I would like to replace the double line gap with a single line instead. Such as:

 This is a test sentence 1.
 This is a test sentence 2.
 This is a test sentence 3.
 This is a test sentence 4.
 This is a test sentence 5.

However, I do not know how to detect the double line break, "\\n" works when replacing a single line break but i have tried "\\n\\n" in a replace function with no success.

textView.setText(string.replaceAll("\n\n","\n"));

You could use:

str.replaceAll("[\r\n]+", "\n") 

Source: Remove multiple linebreaks

You can use below code, It will replace the double lines to single line.

string = Pattern.compile("[\r\n]+").matcher(string).replaceAll("\n");
textView.setText(string);

or

 string = string.replaceAll("[\r\n]+", "\n");
 textView.setText(string);

Both should give the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM