Programming Tips - C/C++: Example use of use strtok_r()

Date: 2010mar15 Update: 2026oct1 Language: C/C++ Keywords: strtok, strtok_s_l, Microsoft Visual C++ Q. C/C++: Example use of use strtok_r() A. Here's an example. This function uses strtok_r() to break up a string that is delimited by semi-colons and commas.
// Linux // Warning: klobbers input string void BreakOnPunct(char *s) { const char * delim = ";,"; // Your choice of delimiters char * save; char * p; for (p = strtok_r(s, delim, &save); p; p = strtok_r(NULL, delim, &save)) { printf("chunk=%s\n", p); } }
In older MSVC++ there is strtok_s() which is used just the same:
// Windows // Warning: klobbers input string void BreakOnPunct(LPSTR s) { LPCSTR delim = ";,"; // Your choice of delimiters LPSTR save; LPSTR p; for (p = strtok_s(s, delim, &save); p; p = strtok_s(NULL, delim, &save)) { printf("chunk=%s\n", p); } }
Full Example Use (Linux):
#include <string.h> #include <stdio.h> // (Place function BreakOnPunc() from above here) int main() { char buf[100] = "one,two;three"; BreakOnPunct(buf); // buf is now klobbered }
Output:
chunk=one chunk=two chunk=three