OneBite.Dev - Coding blog in a bite size

split a string by comma sign in C

Code snippet on how to split a string by comma sign in C

  char *split_string(char *string) 
  { 
  	char *comma_ptr = strchr(string, ','); 
	if (comma_ptr) 
	{ 
		*comma_ptr = '\0'; 
		return comma_ptr + 1; 
	} 
	return NULL; 
  }   

This code is used to split a string by the comma sign. It takes the string as an argument. A variable holds a pointer to the location of the comma sign in the string using the library function ‘strchr’. If there is a comma, the pointer changes the comma sign to be a null character, then it returns a pointer to where the comma sign was replaced. If there is no comma sign, then the function returns a ‘NULL’. This allows the string to be split by the comma sign without modifying the original string.

c