Split String

Hello all! I've just spent... too long coding this, and I was wondering if there was an easier way... Or if perhaps this code could be simplified...

static int countInstances(String haystack, char needle) {
  int count = 0;
  for(int i=0; i < haystack.length(); i++) {
    if(haystack.charAt(i) == needle) count++;
  }
  return count;
}

static void splitString(String haystack, char needle, int count, String output[]) {
  int startpos = 0;
  
  for(int i=0; i < count; i++) {
    int i2;
    for(i2=startpos; i2 < haystack.length(); i2++) {
      if(haystack.charAt(i2) == needle) break;
    }
    
    output[i] = haystack.substring(startpos, i2);
    startpos = i2+1;
  }
  output[count] = haystack.substring(startpos);
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  String input = "This,is,a,test";
  char delimeter = ',';
  
  int count = countInstances(input, delimeter);
  String TestArray[count+1]; // Add one so that the element on the end doesn't cause the world to end...!
  splitString(input, delimeter, count, TestArray);
  
  // Do something with it:
  
  Serial.print("Length of Array: ");
  Serial.println(sizeof(TestArray) / sizeof(String));
  
  for(int i = 0; i < (sizeof(TestArray) / sizeof(String)); i++) {
    Serial.print("\"");
    Serial.print(TestArray[i]);
    Serial.print("\" ");
  }
  Serial.println();
  
  // Someone set up us the bomb.
  for(;;);
}

Thanks!

How's this ...

void setup() {
  Serial.begin(9600);
}

void loop() {
  char input[] = "This,is,a,test";
   
  char* p = strtok(input, ",");
  while (p) {
    Serial.print("\"");
    Serial.print(p);
    p = strtok(NULL, ",");
    Serial.print("\" ");
  }
  Serial.println();
  
  for(;;);
}

Thank you very much, this has been most helpful. Had some fun with chars and strings... but got there in the end!

Thanks again!