JAVA - 在 30 个字符后的下一个空格处插入一个新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1033563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAVA - Inserting a new line at the next space after 30 characters
提问by Kevin Stich
I have a large block of text (200+ characters in a String) and need to insert new lines at the next space after 30 characters, to preserve words. Here is what I have now (NOT working):
我有一大块文本(字符串中有 200 多个字符),需要在 30 个字符后的下一个空格处插入新行,以保留单词。这是我现在拥有的(不工作):
String rawInfo = front.getItemInfo(name);
String info = "";
int begin = 0;
for(int l=30;(l+30)<rawInfo.length();l+=30) {
while(rawInfo.charAt(l)!=' ')
l++;
info += rawInfo.substring(begin, l) + "\n";
begin = l+1;
if((l+30)>=(rawInfo.length()))
info += rawInfo.substring(begin, rawInfo.length());
}
Thanks for any help
谢谢你的帮助
采纳答案by coobird
As suggested by kdgregory, using a StringBuilder
would probably be an easier way to work with string manipulation.
正如 kdgregory 所建议的那样,使用 aStringBuilder
可能是处理字符串操作的一种更简单的方法。
Since I wasn't quite sure if the number of characters before the newline is inserted is the word before or after 30 characters, I opted to go for the word after 30 characters, as the implementation is probably easier.
由于我不太确定插入换行符之前的字符数是 30 个字符之前还是之后的单词,因此我选择了 30 个字符之后的单词,因为实现可能更容易。
The approach is to find the instance of the " "
which occurs at least 30 characters after the current character which is being viewed by using StringBuilder.indexOf
. When a space occurs, a \n
is inserted by StringBuilder.insert
.
方法是" "
使用StringBuilder.indexOf
. 当出现空格时, a\n
被插入StringBuilder.insert
。
(We'll assume that a newline is \n
here -- the actual line separator used in the current environment can be retrieved by System.getProperty("line.separator");
).
(我们假设\n
这里有一个换行符——当前环境中使用的实际行分隔符可以通过 检索System.getProperty("line.separator");
)。
Here's the example:
这是示例:
String s = "A very long string containing " +
"many many words and characters. " +
"Newlines will be entered at spaces.";
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + 30)) != -1) {
sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());
Result:
结果:
A very long string containing many many words and characters. Newlines will.
I should add that the code above hasn't been tested out, except for the example String
that I've shown in the code. It wouldn't be too surprising if it didn't work under certain circumstances.
我应该补充一点,除了String
我在代码中显示的示例之外,上面的代码还没有经过测试。如果它在某些情况下不起作用也就不足为奇了。
Edit
编辑
The loop in the sample code has been replaced by a while
loop rather than a for
loop which wasn't very appropriate in this example.
示例代码中的while
循环已被替换为循环,而不是for
在此示例中不太合适的循环。
Also, the StringBuilder.insert
method was replaced by the StringBuilder.replace
method, as Kevin Stich mentioned in the comments that the replace
method was used rather than the insert
to get the desired behavior.
此外,该StringBuilder.insert
方法被方法取代StringBuilder.replace
,正如 Kevin Stich 在评论中提到的那样,使用该replace
方法而不是insert
来获得所需的行为。
回答by kdgregory
A better solution: copy the string into a StringBuilder so that you can insert / change characters without a lot of substring mucking. Then use the indexOf() method that takes a starting position to find the index to change.
更好的解决方案:将字符串复制到 StringBuilder 中,这样您就可以插入/更改字符,而无需进行大量子字符串处理。然后使用采用起始位置的 indexOf() 方法来查找要更改的索引。
Edit: teh codez:
编辑: teh codez:
public static String breakString(String str, int size)
{
StringBuilder work = new StringBuilder(str);
int pos = 0;
while ((pos = work.indexOf(" ", pos + size)) >= 0)
{
work.setCharAt(pos, '\n');
}
return work.toString();
}
回答by Bill K
I would iterate over the string instead of the 30. You have to track the 30 though.
我会遍历字符串而不是 30。不过你必须跟踪 30。
psuedocode because this sounds like homework:
伪代码,因为这听起来像作业:
charInLine=0
iterateOver each char in rawString
if(charInLine++ > 30 && currChar==' ')
charInLine=0
currChar='\n'
回答by Carl Manaster
Here's a test-driven solution.
这是一个测试驱动的解决方案。
import junit.framework.TestCase;
public class InsertLinebreaksTest extends TestCase {
public void testEmptyString() throws Exception {
assertEquals("", insertLinebreaks("", 5));
}
public void testShortString() throws Exception {
assertEquals("abc def", insertLinebreaks("abc def", 5));
}
public void testLongString() throws Exception {
assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 1));
assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 2));
assertEquals("abc\ndef\nghi", insertLinebreaks("abc def ghi", 3));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 4));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 5));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 6));
assertEquals("abc def\nghi", insertLinebreaks("abc def ghi", 7));
assertEquals("abc def ghi", insertLinebreaks("abc def ghi", 8));
}
public static String insertLinebreaks(String s, int charsPerLine) {
char[] chars = s.toCharArray();
int lastLinebreak = 0;
boolean wantLinebreak = false;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
if (wantLinebreak && chars[i] == ' ') {
sb.append('\n');
lastLinebreak = i;
wantLinebreak = false;
} else {
sb.append(chars[i]);
}
if (i - lastLinebreak + 1 == charsPerLine)
wantLinebreak = true;
}
return sb.toString();
}
}
回答by Carl Manaster
Maybe I am missing something. Whats wrong with
也许我错过了一些东西。怎么了
String s = ... s = s.substring(0, 30) + s.substring(30).replace(' ', '\n');
String s = ... s = s.substring(0, 30) + s.substring(30).replace(' ', '\n');
This replaces all spaces with newlines starting after character 30.
这将用字符 30 之后开始的换行符替换所有空格。
Its slightly less efficient but for 200 characters it really doesn't matter (that is extremely small for data manipulation).
它的效率稍低,但对于 200 个字符,这真的无关紧要(这对于数据操作来说非常小)。
Bruce
布鲁斯
回答by Ahmed Chowdhury
String s = "A very long string containing " +
"many many words and characters. " +
"Newlines will be entered at spaces.";
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + 30)) != -1) {
sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());
this is the correct one i also tried this.
这是正确的,我也试过。