简体   繁体   中英

splitting a StringBuilder value without String.split()

I'll be processing texts and will split along the way for one, its substrings on regular expressions like String.split() does. i'm looking to do these on StringBuilder for speed concerns.

From what i know, StringBuilder has no such method. all i can do is to invoke String.split() and turn the result into StringBuilder []. however, this would be slow-- String.split() interns every entry of String[] it produces.

Also - StringBuilder isn't overriding Object.equals() . when i need to use StringBuilder as the type in collections, i'm writing a wrapper class that has a StringBuilder value-field and overriding equals() on the values of this field to get it right.

these are the 2 so far i can recall that i needed to have and that came short.

My Q is:

Am i missing something here - is there a way to get these functionalities on StringBuilder without having String in between to slow it down?

If not - why not? The main reason-for-being of StringBuilder is the execution time at the cost of memory-- as alternative to String's efficient memory with slow execution(?) And StringBuilder is a type for texts. why wouldn't it have these directly-- split() for one?

TIA.

StringBuilder is a CharSequence too.

Pattern pattern = Pattern.compile(",\\s*"); // Best static final.
Matcher m = pattern.matcher(stringBuilder);
int pos0 = 0;
while (m.find()) {
    int pos1 = m.start();
    CharSequence cs = stringBuilder.subSequence(pos0, pos1);
    ...
    pos0 = pos1;
}
CharSequence cs = stringBuilder.subSequence(pos0, stringBuilder.length());
...

Of course s being either CharSequence or String. A String could utilize String.substring which does not allocate a new char array.

A regular expression still is slow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM