您的位置:首页 > 其它

c 字符串操作函数strtok、strstr、strchr备忘

2017-08-15 10:38 465 查看
今天遇到平时比较少用的这三个字符串函数,查资料并测试了一下,备忘。。。

头文件:#include <string.h>
1、定义函数:char * strtok(char *s, const char *delim);
函数说明:strtok()用来将字符串分割成一个个片段. 参数s 指向欲分割的字符串, 参数delim 则为分割字符串,当strtok()在参数s 的字符串中发现到参数delim 的分割字符时则会将该字符改为\0
字符. 在第一次调用时,strtok()必需给予参数s 字符串, 往后的调用则将参数s 设置成NULL. 每次调用成功则返回下一个分割后的字符串指针.
返回值:返回下一个分割后的字符串指针, 如果已无从分割则返回NULL.

2、  定义函数:char *strstr(const char *haystack, const char * needle);
函数说明:strstr()会从字符串haystack 中搜寻字符串needle, 并将第一次出现的地址返回.
返回值:返回指定字符串第一次出现的地址, 否则返回0.

3、  定义函数:char * strchr (const char *s, int c);
        函数说明:strchr()用来找出参数s 字符串中第一个出现的参数c 地址, 然后将该字符出现的地址返回.

       返回值:如果找到指定的字符则返回该字符所在地址, 否则返回0.

其实2、3这两个函数差不多,只不过一个是子串,一个是字符。

[cpp] view
plain copy

//一些不常用的字符串函数备忘  

//str_test.c  

#include <stdio.h>  

#include <string.h>  

  

void strtok_test()//字符串分割  

{  

         char s[] = "ab-cd:123fez-o:hello,world!";  

         char *delim = "-:,f";  

         char *p;  

         int i=1;  

        fprintf(stdout,"s =ab-cd:123fez-o:hello,world! delim=%s\nstrtok_test print:%d %s ", delim ,i,strtok(s, delim));  

         while((p = strtok(NULL, delim)))  

              printf("%d %s ",++i, p);  

         printf("\n");  

}  

void strstr_test()//字符串查找  

{  

         char * s = "123abc";  

         char *p;  

         p = strstr(s, "3a");  

         printf("strstr_test print: %s\n", p);  

}  

void strchr_test()//找出字符在字符串第一次出现的位置  

{  

        char *addr="192.168.1.1";  

        char *p;  

        p=addr;  

        p=strchr(p,'.');  

        printf("strchr_test print: %s\n",p);  

  

}  

  

int main()  

{  

        strtok_test();  

        strstr_test();  

        strchr_test();  

        return 0;  

结果:

[huangbin@localhost test]$ gcc str_test.c

[huangbin@localhost test]$ ./a.out

s =ab-cd:123fez-o:hello,world! delim=-:,f

strtok_test print:1 ab 2 cd 3 123 4 ez 5 o 6 hello 7 world!

strstr_test print: 3abc

strchr_test print: .168.1.1

[huangbin@localhost test]$
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: