Duplicate and incorrect result trying to append String to Custom StringBuilder

286 Views Asked by At

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?

1

There are 1 best solutions below

3
On BEST ANSWER

You are always passing to writeLine the entire input CharSequence, and writeLine always appends the characters of the input String starting at the first character.

Therefore, the first call to writeLine appends

    this = "is"

and the second call appends

    this = "is"
a = "test"

You can pass another argument to writeLine:

private void writeLine(String str, int from, int to) {
    if (beginningOfLine && to > 0) {
        writeIndent();
        beginningOfLine = false;
    }
    stringBuilder.append(str, from, to);
}

and call it from append as follows:

public IndentingStringBuilder append(CharSequence csq, int start, int end) {
    int from = 0;
    while (start < end) {
        if (csq.charAt(start) == '\n') {
            writeLine(csq.toString(), from, start);
            from = start + 1;
            stringBuilder.append(newLine);
            beginningOfLine = true;
            start++;
        } else {
            start++;
        }
    }
    writeLine(csq.toString(), from, start);
    return this;
}

As an alternative, you can pass to writeLine a subSequence of csq.