We often deal with strings in a C program and we want to split the strings into small tokens on the basis of delimiter. We can do this easily. Lets scan each character of the string from the beginning and put NULL whenever it matches the delimiter character. We have a static variable to store the last token position. This advances as we obtain a token and move to the next posotion. Below is a stepping diagram and C code of this process.
Input String: "A Quick Brown Fox Jumps over the lazy dog." Tokenize process: Token 1: "A\0Quick Brown Fox Jumps over the lazy dog." Position^ Token 2: "A\0Quick\0Brown Fox Jumps over the lazy dog." Position^ Token 3: "A\0Quick\0Brown\0Fox Jumps over the lazy dog." Position^ Token 4: "A\0Quick\0Brown\0Fox\0Jumps over the lazy dog." Position^ Token 5: "A\0Quick\0Brown\0Fox\0Jumps\0over the lazy dog." Position^ Token 6: "A\0Quick\0Brown\0Fox\0Jumps\0over\0the lazy dog." Position^ Token 7: "A\0Quick\0Brown\0Fox\0Jumps\0over\0the\0lazy dog." Position^ Token 8: "A\0Quick\0Brown\0Fox\0Jumps\0over\0the\0lazy\0dog." Position^ Token 9: "A\0Quick\0Brown\0Fox\0Jumps\0over\0the\0lazy\0dog\0" Position^
We do not require to do all the steps as C runtime library has strtok() function to do all these for us. Here is a sample example program.
Note: Buffer allocated by strdup should be released with free(). strtok(), strrev() etc are some utility functions modify its input buffer and produce the result. This is why we should not pass a constant string. CPU will produce a access violation while execution. strdup() is usedful for these cases.
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Questions index C Questions C++ Questions Win32 MFC COM/DCOM DLL Questions
Compilers & Editors
Download Visual Studio Download XCode Download Visual Studio Code Android studio install sdk Eclipse installer Best C compilers IDEs
Development system setup
Windows media creation tool MSDN subscription Ubuntu virtualbox
New updated posts
Why learn C? Calculate weighted average