I'm trying to append a String to StringBuilder I have the code setup.
This is what I am inputting
this = "is"\na = "test"
This is the output I'm getting
this = "is"
this = "is"
a = "test"
my expected output is
this = "is"
a = "test"
Here is my code that is doing the work. I have a class that implements
the following classes CharSequence, Appendable, Serializable
and then I override the append using the code below
@Override
public IndentingStringBuilder append(CharSequence csq) {
append(csq, 0, csq.length());
return this;
}
@Override
public IndentingStringBuilder append(CharSequence csq, int start, int end) {
while (start < end) {
if (csq.charAt(start) == '\n') {
writeLine(csq.toString(), start);
stringBuilder.append(newLine);
beginningOfLine = true;
start++;
} else {
start++;
}
}
writeLine(csq.toString(), start);
return this;
}
private void writeLine(String str, int end) {
if (beginningOfLine && end > 0) {
writeIndent();
beginningOfLine = false;
}
stringBuilder.append(str, 0, end);
}
private void writeIndent() {
for (int i = 0; i < indentLevel; i++) {
stringBuilder.append(' ');
}
}
this are the global vars defined
private static final String newLine = System.getProperty("line.separator");
private int indentLevel = 0;
private StringBuilder stringBuilder = new StringBuilder();
What am I doing wrong here? and how would I fix this to get correct results for my input?
You are always passing to
writeLinethe entire inputCharSequence, andwriteLinealways appends the characters of the inputStringstarting at the first character.Therefore, the first call to
writeLineappendsand the second call appends
You can pass another argument to
writeLine:and call it from
appendas follows:As an alternative, you can pass to
writeLineasubSequenceofcsq.