I have the following string:
A:B:1111;domain:80;a;b
The A is optional so B:1111;domain:80;a;b is also valid input.
The :80 is optional as well so B:1111;domain;a;b or :1111;domain;a;b are also valid input
What I want is to end up with a String[] that has:
s[0] = "A";
s[1] = "B";
s[2] = "1111";
s[3] = "domain:80"
s[4] = "a"
s[5] = "b"
I did this as follows:
List<String> tokens = new ArrayList<String>();
String[] values = s.split(";");
String[] actions = values[0].split(":");
for(String a:actions){
tokens.add(a);
}
//Start from 1 to skip A:B:1111
for(int i = 1; i < values.length; i++){
tokens.add(values[i]);
}
String[] finalResult = tokens.toArray();
I was wondering is there a better way to do this? How else could I do this more efficiently?
There are not many efficiency concerns here, all I see is linear.
Anyway, you could either use a regular expression or a manual tokenizer.
You can avoid the list. You know the length of
valuesandactions, so you can doIt should be reasonably efficient, unless you insist on implementing
splityourself.Untested low-level approach (make sure to unit test and benchmark before use):
Note: this code is optimized in the crazy way of that it will consider a
:only in the first component. Handling the last component is a bit tricky, asoutwill have the value-1.I would usually not use this last approach, unless performance and memory is extremely crucial. Most likely there are still some bugs in it, and the code is fairly unreadable, in particulare compare to the one above.