C语言字符串操作

strtok

  • 定义:char *strtok(char s[], const char *delim);

  • s为要分解的字符串

  • delim为分隔符字符串

  • 当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针

    #include 
    #include 
    
    void printArr(char *, int);
    
    int main() {
        char s[30] = "abc dedef  gdhi    de    jkl";
        const char *delim = "de";
        printArr(s, 30);
        printf("\n");
        char *result = strtok(s, delim);
        while (result) {
            printf("%s|%s\n", result, s);
            result = strtok(NULL, delim);
        }
        printArr(s, 30);
        return 0;
    }
    
    void printArr(char *s, int n) {
        for (int i = 0; i < n; i++) {
            printf("[%c#%-3d] ", s[i], s[i]);
        }
    }
    

    结果:

    [a#97 ] [b#98 ] [c#99 ] [ #32 ] [d#100] [e#101] [d#100] [e#101] [f#102] [ #32 ] [ #32 ] [g#103] [d#100] [h#104] [i#105]
    [ #32 ] [ #32 ] [ #32 ] [ #32 ] [d#100] [e#101] [ #32 ] [ #32 ] [ #32 ] [ #32 ] [j#106] [k#107] [l#108] [ #0  ] [ #0  ]
    
    abc |abc
    f  g|abc
    hi    |abc
        jkl|abc
    [a#97 ] [b#98 ] [c#99 ] [ #32 ] [ #0  ] [e#101] [d#100] [e#101] [f#102] [ #32 ] [ #32 ] [g#103] [ #0  ] [h#104] [i#105]
    [ #32 ] [ #32 ] [ #32 ] [ #32 ] [ #0  ] [e#101] [ #32 ] [ #32 ] [ #32 ] [ #32 ] [j#106] [k#107] [l#108] [ #0  ] [ #0  ]
    
C语言字符串操作_第1张图片
4.png

注意:

  • 分割的字符串不能为常量
  • 第一次调用需要传入需要分割的字符串,后面就传入NULL。
  • 如果未找到分割的字符串,则范围当前字符串的指针
  • 所有出现分割字符串的地方都会被过滤, 如上面代码 dede
  • strtok会破坏被分解的字符串,调用前后不一致。我们看到运行结果,所有出现de的地方,第一个字符被替换成了'\0'。

strchr

  • 定义:char strchr(const char _Str,char _Val)

  • 回首次出现_Val的位置的指针,返回的地址是被查找字符串指针开始的第一个与Val相同字符的指针,如果Str中不存在Val则返回NULL。

  • 返回值:成功则返回要查找字符第一次出现的位置,失败返回NULL

    int main() {
        char s[30] = "abc dedef  gdhi    de    jkl";
        char *result = strchr(s, 'd');
        printf("%s\n", result);
        return 0;
    }
    

    结果:

    dedef  gdhi    de    jkl
    

strstr

  • 定义:char *strstr (const char *, const char *)
  • 判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL

你可能感兴趣的:(C语言字符串操作)