strtok函数源码
时间: 2023-10-18 07:57:06 浏览: 114
以下是一个简化版的strtok函数的源码实现:
```c
#include <stdio.h>
#include <string.h>
char *strtok(char *str, const char *delim) {
static char *nextToken = NULL; // 保存下一个分割的位置
if (str != NULL) {
nextToken = str;
}
// 如果没有字符串需要分割,直接返回NULL
if (nextToken == NULL || *nextToken == '\0') {
return NULL;
}
// 跳过分隔符
while (*nextToken != '\0' && strchr(delim, *nextToken) != NULL) {
nextToken++;
}
// 找到下一个分隔符的位置
char *start = nextToken;
while (*nextToken != '\0' && strchr(delim, *nextToken) == NULL) {
nextToken++;
}
// 替换分隔符为字符串结束符,并返回子字符串指针
if (*nextToken != '\0') {
*nextToken = '\0';
nextToken++;
return start;
}
return start;
}
int main() {
char str[] = "Hello, World! This is a test string.";
const char delim[] = " ,.!"; // 分隔符
char *token = strtok(str, delim);
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, delim);
}
return 0;
}
```
以上代码将字符串"Hello, World! This is a test string."按照空格、逗号和句号进行分割,并
阅读全文