zoukankan      html  css  js  c++  java
  • strncmp strstr____asderwsde,寻找其中的一个子字符串比如sde的个数

    编写一个函数,已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,如果没有返回0,有的话返回子字符串的个数。函数的原型为

    int num_of_substring(const char* string,const char *substring);



    利用strncmp

    函数名: strncmp
    功 能: 串比较
    用 法: int strncmp(char *str1, char *str2, int maxlen);
    说明:此函数功能即比较字符串str1和str2的前maxlen个字符。
    如果前maxlen字节完全相等,返回值就=0;在前maxlen字节比较过程中,如果出现str1[n]与str2[n]不等,则返回(str1[n]-str2[n])。


    利用strstr

    包含文件:string.h
    函数名: strstr
    函数原型:extern char *strstr(char *str1, char *str2);
    功能:查找完全匹配的子字符串。
    返回值:返回该位置的指针,如找不到,返回空指针。

    代码利用strstr
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    
    int num_of_substring(const char* string,const char *substring)
    {
        int count = 0, length = strlen(substring);
        const char *p = string;
    
        while( (p = strstr(p, substring)) != NULL )
        {
            //puts(p);//test
            p += length;
            count++;
        }
        return count;
    }
    int main()
    {
        char a1[] = "asderwsdejeifsderjwapfsdeejoirjwae";
        char a2[] = "sde";
    
        printf("%d\n", num_of_substring(a1, a2));
        return 0;
    }
  • 相关阅读:
    移植nand驱动补缺:make mrproper与make clean以及make distclean,find/grep. makefile
    repo使用
    git使用总结
    notepade++使用
    linux内核源代码、配置与编译
    linux内核介绍
    块设备
    PHP和javascript中url编码解码详解
    python中的类方法、静态方法、对象方法
    webpack+vue中安装使用vue-layer弹窗插件
  • 原文地址:https://www.cnblogs.com/wwjyt/p/3153126.html
Copyright © 2011-2022 走看看