文章目录


字符串中查找字符 strchr()

描述

C 库函数 char _strchr(const char _str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。


声明

下面是 strchr() 函数的声明。

char *strchr(const char *str, int c)

    参数

    str – 要被检索的 C 字符串。
    c – 在 str 中要搜索的字符。


    返回值

    该函数返回在字符串 str 中第一次出现字符 c 的位置,如果未找到该字符则返回 NULL。

    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
       const char str[] = "http://www.runoob.com";
       const char ch = '.';
       char *ret;
    
       ret = strchr(str, ch);
    
       printf("|%c| 之后的字符串是 - |%s|\n", ch, ret);
       
       return(0);
    }
    

    结果为:

    |.| 之后的字符串是 - |.runoob.com|
    

    字符串分割 strtok()

    描述

    C 库函数 char _strtok(char _str, const char _delim) 分解字符串 str 为一组字符串,delim 为分隔符。


    声明

    下面是 strtok() 函数的声明。

    char *strtok(char *str, const char *delim)

    参数

    str – 要被分解成一组小字符串的字符串。
    delim – 包含分隔符的 C 字符串。


    返回值

    该函数返回被分解的第一个子字符串,如果没有可检索的字符串,则返回一个空指针。

    #include <string.h>
    #include <stdio.h>
     
    int main () {
       char str[80] = "This is - www.runoob.com - website";
       const char s[2] = "-";
       char *token;
       
       /* 获取第一个子字符串 */
       token = strtok(str, s);
       
       /* 继续获取其他的子字符串 */
       while( token != NULL ) {
          printf( "%s\n", token );
        
          token = strtok(NULL, s);
       }
       
       return(0);
    }
    

    结果为:

    This is 
     www.runoob.com 
     website


    自己的函数

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main()
    {
        char str[] = "标签坐标: X = 28889 cm , Y = 36 cm, Z = 8 cm";
        char *token;
        int XPos=0, YPos=0, ZPos=0;
        
        /* 获取第一个子字符串 */
        token = strtok(str, " ");
        //printf("%s\n", token);
        /* 继续获取其他的子字符串 */
        while (token != NULL)
        {   
            if (*token == 'X')
            {   
                token = strtok(NULL, " ");  //printf("%s\n", token);
                token = strtok(NULL, " ");  //printf("XPos=%s\n", token);
                XPos = atoi(token);
            }
            if (*token == 'Y')
            {   
                token = strtok(NULL, " ");  //printf("%s\n", token);
                token = strtok(NULL, " ");  //printf("YPos=%s\n", token);
                YPos = atoi(token);
            }
            if (*token == 'Z')
            {   
                token = strtok(NULL, " ");  //printf("%s\n", token);
                token = strtok(NULL, " ");  //printf("ZPos=%s\n", token);
                ZPos = atoi(token);
            }
            token = strtok(NULL, " ");  //printf("%s\n", token);
        }
        printf("%d\n", XPos);
        printf("%d\n", YPos);
        printf("%d\n", ZPos);
        return (0);
    }
    

    结果为:

    28889
    36
    8

      Ref:

      1. C 库函数 - strchr()
      2. C语言中常见的字符串处理函数
      3. C 库函数 - strtok()