1

When we extend DefaultHandler, we usually override the characters function.

I was wondering which would be a more efficient way to extract the String supplied...


  1. Would it be using a for loop and a StringBuilder?

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        StringBuilder sb = new StringBuilder(length); 
        for(int i=start; i<start+length; i++)
            sb.append(ch[i]);
        String values = sb.toString();
    }
    
  2. Would it be using a simple substring?

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String values = (new String(ch)).substring(start, start + length);
    }
    
  3. Is there another approach?

4
  • 1
    Note that the #characters(char[] ch, int, int) method may be called several times in a row and you should append character data in a StringBuilder class member and not process it until you hit the relevant #endElement(String,String,String) call. Appending chunks of characters should be done by calling StringBuilder#append(char[], int, int). Commented May 28, 2012 at 11:17
  • @Jens You are correct! I have been working a lot with feeds and I noticed this behavior. The problem is that it will be too messy to use a StringBuilder to append (especially for the part of maintaining reference). I prefer to use string concatenation in this case. Commented May 28, 2012 at 13:15
  • If you are implementing ContentHandlers manually you should probably consider using some sort of framework - even a simple one like the built in android.sax would probably simply things for you. Commented May 28, 2012 at 13:19
  • I have worked on a small utility that creates the handlers. I intend to further work on it but not having time though. sherifandroid.blogspot.com/2011/10/sax-class-generator-v10.html Commented May 28, 2012 at 13:24

2 Answers 2

5

There is a constructor that takes a char[] and a range, if that is what you are looking for:

new String(ch, start, length);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh and needless to say, it will perform better than any.
0

String Class has new constructor which can fulfil your requirements as follows

1) new String(char[] value)

2) new String(char[] value, int StartIndex, int numberOfCharacter)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.