字符串查找函数

#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;
}

猜你喜欢

转载自blog.csdn.net/wsw136474/article/details/82390480