Hello Oliver,
Well I have few suggestions for you that *might* make your code work
faster. By looking at the statement below
int nbr = substr_count(sep, str)+1;
String[] result = new String[nbr];
i conclude that you are counting number of space/separator chars in
your string to asses the length of array to be allocated. Then you
start extracting the individual tokens from the string by passing over
the string in a single pass. The problem here is that in all you are
passing over the entire string two times. So if we can reduce it to one
pass then you code may be Twice as fast!!.
I suggest that you use StreamTokenizer class. This will greatly reduce
the complecity/length of you code and moreover will make it fast as its
method may we writtern as native methods. I am giving you below a
sample code:
import java.io.*;
import java.util.*;
public class Main2 {
public static Vector explode(String str) throws IOException
{ StringReader sr=new StringReader(str);
StreamTokenizer stz=new StreamTokenizer(sr);
//Vector to hold tokens. Cannot use other containers as
//MS-JVM is 1.1 based.
Vector vct=new Vector(str.length()/4);
//intial capacity of vector aproximated to number of chars
// to improve speed. However it might waste memory space
stz.resetSyntax();
stz.wordChars(0,0xff);
stz.whitespaceChars(' ',' '); // add your seperator charecters
here
// i am assuming space as the only separator
while(stz.nextToken()!=stz.TT_EOF) // this loop iterators through
the string
vct.add(stz.sval); // returning only a parsed tokens
//ps: if memory usage is to be minimized then call
vct.trimToSize() here
// though it might take some time
return vct; // return the vector from the method
}
public static void main(String[] args) throws Exception
{ Vector v= explode(" \"Hello There\" ,how are you hi there");
java.util.Enumeration eu= v.elements();//request the enumeration
//MS-JVM provides no iterators but only enumeratios hence you are
stuck
while(eu.hasMoreElements()) //iterate
System.out.println((String)eu.nextElement()); //print tokens
}
}
/*************************Code Ends******************************/
/**************************Output******************************/
"Hello
There"
,how
are
you
hi
there
/**************************Output Ends******************************/
In the above code i have used a Vector instead on array because we
don't know how much words are there in the string. This is done to
ensure that we pass over the entire string only once. however we do
know that each word in approx 3-4 charecters wide(as you said). Thats
why we have provided the vector with an approx required capacity to
improve allocation speed. Rest of the code is self explainatory.
I hope that it will work faster than you code. However i have not
tested it yet. Please let me know if you find any bugs in this code.