这是整个程序的一部分。我遇到的问题是,当给定n时,程序应该在当前或最后一个空格处插入一个新的行字符,以确保在插入新的行字符之前字符计数(空格不包括在count中)永远不会超过n。它当前的行为是用新的行字符拆分单词。保证:n永远不会超过最大单词的字符数。例:n = 9,生存还是毁灭,这是个问题。期望行为:
To be or not
to be that
is the
question
当前行为:To be or not
to be th
at is
the question
可以看到,空格没有像预期的那样被替换,单词被新的行字符分隔。我检查了好几次,似乎找不到问题。请帮助!
public class Separator {
int n; //the int in front of read line
int cCount = 0; //character counter
int i;
int lastSpc;
char c; //for character iterator
String linePart;
public String separate(int n, String linePart) {
StringBuilder finLine = new StringBuilder(linePart);
for (i = 0; i < linePart.length(); i++) { //inspects each character in string.
c = linePart.charAt(i);
if (c == ' ') { //determines whether or not char is a space
if (cCount == n ) { //checks char count
finLine.replace(i, i, System.lineSeparator()); //adds new line if char count is reached right before space.
cCount = 0;
lastSpc = i;
}
else {
lastSpc = i; //assigns index to variable so no need to reverse through string.
}
}
else {
cCount++;
if (cCount == n) { //if char count is reached while inspecting letter,
finLine.replace(lastSpc, lastSpc, System.lineSeparator()); //replaces last space with new line char
cCount = i - lastSpc;
}
}
}
return finLine.toString();
}
}
添加第一个换行符后,finLine中的索引不再匹配linePart中的索引。使用finLine代替linePart来保持索引的一致性。
public String separate(int n, String linePart) {
StringBuilder finLine = new StringBuilder(linePart);
int lines_added = 0;
for (i = 0; i < finLine.length(); i++) { //inspects each character in string.
c = finLine.charAt(i);
if (c == ' ') { //determines whether or not char is a space
if (cCount == n ) { //checks char count
finLine.replace(i, i+1, System.lineSeparator()); //adds new line if char count is reached right before space.
cCount = 0;
lastSpc = i ;
}
else {
lastSpc = i; //assigns index to variable so no need to reverse through string.
}
}
else {
cCount++;
if (cCount == n) { //if char count is reached while inspecting letter,
finLine.replace(lastSpc, lastSpc+1, System.lineSeparator()); //replaces last space with new line char
cCount = i - lastSpc;
}
}
}
return finLine.toString();
}