C提供了两个函数strtok()和strtok_r(),用于通过某个分隔符拆分字符串。拆分字符串是一项非常常见的任务。例如,我们有一个以逗号分隔的文件项列表,我们希望在一个数组中包含单个项。 斯特托克()
// Splits str[] according to given delimiters.// and returns next token. It needs to be called// in a loop to get all tokens. It returns NULL// when there are no more tokens.char * strtok(char str[], const char *delims);
C
// A C/C++ program for splitting a string // using strtok() #include <stdio.h> #include <string.h> int main() { char str[] = "Geeks- for -Geeks"; // Returns first token char * token = strtok (str, "-"); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf ("%s", token); token = strtok (NULL, "-"); } return 0; } |
输出:
GeeksforGeeks
strtok_r() 与C中的strtok()函数一样,strtok_r()也执行同样的任务,将字符串解析为一系列标记。strtok_r()是一个 可重入 strtok()的版本 有两种方法可以称为strtok_r()
// The third argument saveptr is a pointer to a char * // variable that is used internally by strtok_r() in // order to maintain context between successive calls// that parse the same string.char *strtok_r(char *str, const char *delim, char **saveptr);
下面是一个简单的C程序,演示strtok_r()的用法:
CPP
// C program to demonstrate working of strtok_r() // by splitting string based on space character. #include <stdio.h> #include <string.h> int main() { char str[] = "Geeks for Geeks"; char * token; char * rest = str; while ((token = strtok_r(rest, " ", &rest))) printf ("%s", token); return (0); } |
输出:
GeeksforGeeks
strtok的另一个例子:
C
// C code to demonstrate working of // strtok #include <stdio.h> #include <string.h> // Driver function int main() { // Declaration of string char gfg[100] = " Geeks - for - geeks - Contribute"; // Declaration of delimiter const char s[4] = "-"; char * tok; // Use of strtok // get first token tok = strtok (gfg, s); // Checks for delimiter while (tok != 0) { printf (" %s", tok); // Use of strtok // go through other tokens tok = strtok (0, s); } return (0); } |
输出:
Geeks for geeks Contribute
实际应用 strtok可以基于一些分隔符将一个字符串拆分为多个字符串。A. 简单CSV文件 可以使用此函数实现支持。CSV文件使用逗号作为分隔符。
C
// C code to demonstrate practical application of // strtok #include <stdio.h> #include <string.h> // Driver function int main() { // Declaration of string // Information to be converted into CSV file char gfg[100] = " 1997 Ford E350 ac 3000.00"; // Declaration of delimiter const char s[4] = " "; char * tok; // Use of strtok // get first token tok = strtok (gfg, s); // Checks for delimiter while (tok != 0) { printf ("%s, ", tok); // Use of strtok // go through other tokens tok = strtok (0, s); } return (0); } |
输出:
1997, Ford, E350, ac, 3000.00,
参考: 1) 手册页strtok_r() 2) http://stackoverflow.com/questions/15961253/c-correct-usage-of-strtok-r 本文由 马扎尔·伊玛目·汗 和 山塔努23 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。