I have this code, which goes through a string and split it using a char delimiter.
I am concerned where it can be improved.
- Main concerns are speed and memory usage with speed as the priority.
- Any other improvements are welcome too.
- Is there a better way (Without regex based split and without 3rd party libraries).
What it does:
- Iterate through string and extract all portions of strings delimited by given
char
- return all portions, including empty ones.
- StringUtility class name is used because in future I can add other utility methods when necessory
Code:
public class StringUtility {
/**
* Split a string using a single char delimiter
* @param strToSplit string to use
* @param delimiter delimiter
* @return String[] of portions
*/
public static String[] split(String strToSplit, char delimiter) {
ArrayList<String> arr = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strToSplit.length(); i++) {
char at = strToSplit.charAt(i);
if (at == delimiter) {
arr.add(sb.toString());
sb = new StringBuilder();
} else {
sb.append(at);
}
}
arr.add(sb.toString());
return arr.toArray(new String[0]);
}
}
Unit Test:
This code currently passes following jUnit Test Cases
public class StringUtilityTest {
@Test
public void test1() {
final String str1 = "Because";
final String str2 = "I'm";
final String str3 = "Batman";
final char delim = ' ';
String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3,
delim);
Assert.assertTrue(parts.length == 3);
Assert.assertTrue(parts[0].equals(str1));
Assert.assertTrue(parts[1].equals(str2));
Assert.assertTrue(parts[2].equals(str3));
}
@Test
public void test2() {
final String str1 = "";
final String str2 = "I'm";
final String str3 = "Batman";
final char delim = ' ';
String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3,
delim);
Assert.assertTrue(parts.length == 3);
Assert.assertTrue(parts[0].equals(str1));
Assert.assertTrue(parts[1].equals(str2));
Assert.assertTrue(parts[2].equals(str3));
}
@Test
public void test3() {
final String str1 = "";
final char delim = ' ';
String[] parts = StringUtility.split(str1,
delim);
Assert.assertTrue(parts.length == 1);
Assert.assertTrue(parts[0].equals(str1));
}
}
Speed Test:
From fastest to slowest
- janos/Heslacher : split using index of and subString
- Emanuele Paolini : split using subString
- janos : split by setting string builder to zero length
- me : original
String#split
already exists. \$\endgroup\$char
without using regex or 3rd party libraries). Any version of java is fair game. You are welcome to post an answer that use enhanced for loops or streams. It will be a nice addition. \$\endgroup\$