I could split it twice with substring() and save both halves seperatly, but since I'm going for efficiency, I need a better solution which ideally saves both halves in a String[] in a single run.
-
1String.Split might be useful here. – Erran Morad Feb 05 '14 at 07:39
-
4What do you mean by "in a single run"? If you're going to have two string objects, calling `substring` twice is about as good as it gets... Also you say you "need" a better solution - what do your performance numbers tell you so far, and what are your performance goals? Have you definitely established that this is the bottleneck in your code? – Jon Skeet Feb 05 '14 at 07:39
-
Can't get more efficient than this: http://stackoverflow.com/questions/3250143/regex-to-split-a-string-in-half-in-java – Georgian Feb 05 '14 at 07:41
2 Answers
As @Jon Skeet already mentioned, you should really analyze the performance, because I can't imagine, that this is actually the bottleneck. However, another solution is splitting the String's char array:
String str = "Hello, World!";
int index = 4;
char[] chs = str.toCharArray();
String part1 = new String(chs, 0, index);
String part2 = new String(chs, index, chs.length - index);
System.out.println(str);
System.out.println(part1);
System.out.println(part2);
Prints:
Hello, World!
Hell
o, World!
This could be a general implementation:
public static String[] split(String str, int index) {
if (index < 0 || index >= str.length()) {
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
char[] chs = str.toCharArray();
return new String[] { new String(chs, 0, index), new String(chs, index, chs.length - index) };
}
The problem with this approach is, it is less(!) efficient, than a simple
substring()
call, because my code creates one more object than if you were using twosubstring()
calls (the array is the additionally created object). In fact,substring()
does exactly what I did in my code, without creating an array. The only difference is, that with callingsubstring()
twice, the index is checked twice. Comparing that to object allocation costs is up to you.

- 1
- 1

- 12,902
- 3
- 38
- 45
Try stringName.split('*')
, where *
is what character you want to split the string at. It returns a String array.

- 433
- 2
- 9
-
Four problems. (1) You need double quotes, not single quotes to delimit the argument. (2) If the character you want to split on is special in a regular expression, you need to escape it. (3) If the character occurs more than once, you get more than two pieces. (4) The character itself is actually dropped from the string, which is clearly not what the OP wants. Example - `"Hello world".split("o")` gives `{"Hell", " w", "rld"}`. This answer deserves downvotes. – Dawood ibn Kareem Feb 05 '14 at 09:33
-
Wow, sorry there, jeez. He could use a special character that is not used very often to split the string. Just trying to help. – Arbiter Feb 05 '14 at 09:43