Sherif elKhatib
Sherif elKhatib

Reputation: 45942

Efficiency with java strings

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?

Upvotes: 1

Views: 141

Answers (2)

Pramod Kumar
Pramod Kumar

Reputation: 8014

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)

Upvotes: 0

Thilo
Thilo

Reputation: 262474

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

new String(ch, start, length);

Upvotes: 5

Related Questions