在Java中将字符串拆分为几个不同的行 [英] Splitting a string on to several different lines in Java
问题描述
我有一个非常长的字符串,由字标点符号和空格组成。我试图修改字符串在每个 x
字符后面添加一个新行( \\\
全字。例如:
I have a very long string consisting of words punctuation and spaces. I am trying to modify the string to add a new line (\n
) after every x
characters but while preserving whole words. For example:
一个邪恶的人类喷洒的无辜学生面对胡椒喷雾
An evil human sprayed innocent students in the face with pepper spray
x = 20
会输出如下:
An evil human sprayed 21 chars
innocent students in 20 chars
the face with pepper 20 chars
spray end of string
如果在 x后插入
字符,则应该允许该单词保持在行上,而在单词末尾插入一个新行。 \\\
If words would be split by inserting a \n
after x
characters, then the word should be allowed to stay on the line, while a new line would be inserted at the end of the word.
推荐答案
我会这样写:
s = s.replaceAll("(.{20,}?)\\s+", "$1\n");
这将找到至少二十个非换行字符的每个实例,后跟一个或多个空格字符,并用换行符替换空格。或者,为了使 x
可以在运行时决定(而不是硬编码为 20
), :
This will find every instance of at least twenty non-newline characters, followed by one or more whitespace characters, and replace the whitespace with a newline. Or, to make x
decidable at run-time (rather than hard-coded as 20
), I'd write:
s = s.replaceAll("(.{" + x + ",}?)\\s+", "$1\n");
这篇关于在Java中将字符串拆分为几个不同的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!