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

今天遇到平时比较少用的这三个字符串函数,查资料并测试了一下,备忘。。。

头文件:#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这两个函数差不多,只不过一个是子串,一个是字符。

//一些不常用的字符串函数备忘
//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]$


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值