如何在特定索引处的字符串中添加换行符?

jav*_*ser 3 java string android

我有一个字符串:

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"
Run Code Online (Sandbox Code Playgroud)

像这样:暂时,programmi \n ........ \n ....... \n

在此字符串中每个长度为20个字符之后,我想在Android中的TextView中放置换行符\n以显示.

dug*_*ggu 6

您必须使用正则表达式来快速有效地完成您的任务.尝试以下代码: -

String str = "....";
String parsedStr = str.replaceAll("(.{20})", "$1\n");
Run Code Online (Sandbox Code Playgroud)

(.{20})将捕获一组20个字符.第二个1美元将放置该组的内容.然后将\n附加到刚刚匹配的20个字符.