字符串查找函数

#include<string>
#include<stdio.h>
using namespace std;

/*在s1中查找s2最后一次出现的位置*/
char* my_strstr(char  * s1,char  *s2) {
     char* current=NULL;
     char* last=NULL;

    if (*s2 != '\0') {
        current = strstr(s1,s2);
        while (current != NULL) {
            last = current;
            current = strstr(last+1,s2);
        }
    }
    return last;
}

int main()
{
    //char strchr(char const * str,int ch); 查找字符ch第一次出现的位置,找到后函数返回一个指向该位置的指针。
    //char strrchr(char const * sttr,int ch);返回的是一个字符串种该字符最后出现的位置(right)
    char hello[30] = "Hello  there honey Hello.";
    char *ans = NULL;
    ans = strchr(hello,'h');
    printf("%d\n",(ans-hello));
    

    //查找任何几个字符
    //char * strpbrk(char const *str,char const *group);返回一个指向str中第一个匹配group中任意一个字符的位置。未找到返回NNULL
    ans = strpbrk(hello,"aeiou");
    printf("%d\n",(ans-hello));

    //查找一个子串strstr
    //char *strstr(char * s1,char * s2);r如果s2为空串返回s1
    ans=my_strstr(hello,"Hello");
    printf("%d\n",(ans-hello));

    //查找标记.strtok从字符串中隔离各个单独的称为标记(token)的部分
    //char* strtok(char* str,char const *sep);sep是个字符串,定义了分隔符的字符集合。strtok找到str的下一个标记,并将其以NULL结尾,然后返回一个指向这个标记的指针
    char* tmp = NULL;
    char* ptr = strtok_s(hello," ",&tmp);
    while (ptr != NULL) {
        printf("%s\n",ptr);
        ptr=strtok_s(NULL," ",&tmp);
    }
    return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值