OneBite.Dev - Coding blog in a bite size

split a string by a delimiter in C

Code snippet on how to split a string by a delimiter in C

  char *splitString(char *str, char delimiter)
  {
  int i = 0;
  static char *output[2];
  output[0] = str;
  
  while (str[i] != '\0') {
   if (str[i] == delimiter) {
    output[1] = &str[i + 1];
    str[i] = '\0';
    break;
   }
   i++;
  }
  
  return output[0];
 }

This code splits a given string (str) by a delimiter (delimiter). It then stores the two resulting strings in the static output array and returns the first string.

Firstly, the loop starts by setting the integer value (i) to 0. Then the output array is set to the given string.

The loop then checks for the given delimiter in the string and when the delimiter is found, the output array is set to the position of the next character after the delimiter. This is then followed by setting the delimiter to null. Lastly, the loop breaks and the first string of the output array is returned.

c