c语言--strtok函数的实现

strtok

微软的实现

用空间来换取时间,用了32个八位空间来记录该字母是否位分隔字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
char *my_strtok(char *string, const char *delimiter)
{
unsigned char *str = NULL;
char arr[ASCII_SIZE] = {0}; //记录每个字符是否为分隔符
const unsigned char *delimit = (const unsigned char *)delimiter;
static unsigned char *last = NULL;

//将分隔符的字符状态置为1
do{
//arr[*delmit / 8] |= (1 << (*delimit % 8));
//
// 1001
// 0111
//
// 1
arr[*delimit >> 3] |= (1 << (*delimit & 7));
}while(*delimit++ != '\0');

if(string == NULL){
//如果传入的字符串为空,则把上次处理的位置赋值给str
str = last;
}else{ //如果不为空,则从字符串的开头处理
str = (unsigned char *)string;
}

//找到处理字符的起始位置
//while(arr[*str / 8] & (1 << (*str % 8))
while(arr[*str >> 3] & (1 << (*str & 7)) && *str){
str++;
}

string = str; //记录下起始位置
for(; *str ; ++str){
//if(arr[*str / 8] & (1 << (*str % 8)))
if(arr[*str >> 3] & (1 << (*str & 7))){
*str++ = '\0';
break ;
}
}
last = str; //记录下次分隔的起始判断位置
if(string == (char *)str){
return NULL;
}else{
return string;
}
}

Contents
  1. 1. strtok
    1. 1.1. 微软的实现
,