Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a newline character in a string at specific indices?

I have a string:

String testString= "For the time being, programming is a consumer job, assembly line coding is the norm, and what little exciting stuff is being performed is not going to make it compared to the mass-marketed cräp sold by those who think they can surf on the previous half-century's worth of inventions forever"

like this: For the time being, programmi \n........\n.......\n

After each length of 20 characters in this string, I want to put a newline character \n for display in a TextView in Android.

like image 566
java new user Avatar asked Jan 11 '23 07:01

java new user


2 Answers

You must have to use regex for achieve your task its fast and efficient. Try below code:-

String str = "....";
String parsedStr = str.replaceAll("(.{20})", "$1\n");

The (.{20}) will capture a group of 20 characters. The $1 in the second will put the content of the group. The \n will be then appended to the 20 characters which have been just matched.

like image 194
duggu Avatar answered Jan 26 '23 06:01

duggu


How about something like that?

String s = "...whateverstring...";  

for(int i = 0; i < s.length(); i += 20) {
    s = new StringBuffer(s).insert(i, "\n").toString();
}
like image 24
Philipp Jahoda Avatar answered Jan 26 '23 06:01

Philipp Jahoda