Java, writing my own split string method

The problem is straightforward, you have one offset walking through finding new matches (pos), and another showing then end of the last place you found a match (start).

public static String[] mySplit(String str, String regex)
{
    Vector<String> result = new Vector<String>;
    int start = 0;
    int pos = str.indexOf(regex);
    while (pos>=start) {
        if (pos>start) {
            result.add(str.substring(start,pos));
        }
        start = pos + regex.length();
        result.add(regex);
        pos = str.indexOf(regex,start); 
    }
    if (start<str.length()) {
        result.add(str.substring(start));
    }
    String[] array = result.toArray(new String[0]);
    return array;
}

This avoid extra looping and copies each character only once. Actually, because of the way that substring works, no characters are ever copied, only small string objects are created pointing to the original character buffer. No concatenation of strings is done at all, which is an important consideration.


I think your problem is that you are allocating storeSplit[] with a length that is longer than you need. If you are allowed to use ArrayList, use that to accumulate your results (and use the ArrayList.toArray() method to get the final return value for your function).

If you can't use ArrayList, then you will need to truncate your array before returning it (your counter variable will be of use in determining the correct length). To do that, you will need to allocate an array of correct length, then use System.arraycopy to populate it. Simpler to use ArrayList, but I don't know the exact requirements of your assignment.


As pointed out in the comments, the problem is that you are setting your array size to the length of the String. Instead, you want to set it to double the number of delimeters. Then, adjust accordingly:

  1. If the first character is a delimiter, subtract one,
  2. If the last character is not a delimiter, add one.
// Calculate number of delimiters in str
int delimiters = str.length() - str.replaceAll(regex, "").length();
// Calculate array size
int arraySize = (delimiters * 2) + (str.startsWith(regex) ? -1 : 0);
arraySize = str.endsWith(regex) ? arraySize : arraySize + 1;
String[] storeSplit = new String[arraySize];

Tags:

Java

String

Split