Java – How do I add a newline character to a string at a specific index?

How do I add a newline character to a string at a specific index?… here is a solution to the problem.

How do I add a newline character to a string at a specific index?

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 now, programmi

\n…….\n…….\n

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

Solution

You must use regular expressions to complete your tasks quickly and efficiently. Try the following code: –

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

(.{ 20}) will capture a set of 20 characters. The second $1 will place the contents of the group. \n will be appended to the 20 characters just matched.

Related Problems and Solutions