Chris G.
Chris G.

Reputation: 25974

StringBuilder appends newline "\n" char

I am using StringBuilder in an xml parser DefaultHandler2. builder is a StringBuilder.

@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
    super.characters(ch, start, length);
    builder.append(ch, start, length);
}

@Override
public void endElement(String uri, String localName, String qName){
    strVar = builder.toString();    
}

The problem is now that StringBuilder appends "\n" new line char? It can also be that builder.setLength(0) is adding the newline.

If I ware to accept this new line, it is not possible to remove the new line char from the string. strVar.removeAll("\\n","") in all possible variations is not working.

Any idear?

Thanks Regards Christian

Upvotes: 0

Views: 1484

Answers (2)

NPE
NPE

Reputation: 500673

Most probably the newline character is part of the ch array. StringBuilder only appends things that you tell it to, and won't append a newline of its own accord.

As to strVar.removeAll("\n", "") not removing the newline, don't forget to use the result of the call:

strVar = strVar.removeAll("\n", "")

Strings in Java are immutable, so simply calling removeAll() won't modify the original string object.

Upvotes: 1

Steve Wellens
Steve Wellens

Reputation: 20640

StringBuilder isn't appending any '\n' chars (unless you tell it to).

The '\n' character is originating elsewhere.

Upvotes: 2

Related Questions