0
点赞
收藏
分享

微信扫一扫

获取相关字符串在数组中首次出现的相对位置

1、用到的相关头文件

#include <stdio.h>
#include <string.h>

2、相关函数简介--strstr(str1,str2)

我们知道strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回 str1字符串从 str2第一次出现的位置开始到 str1结尾的字符串;否则,返回NULL。

但是这里需要注意的是strstr返回的是该字符串在栈地址中的绝对位置,而不是数组中的相对位置

3、对strstr(str1,str2)函数进行改进---目标获取字符串在数组中首次出现的相位位置

int strstrs(char *str1,char *str2)
{
  return (strstr(str1, str2)-str1);
}

4、程序测试

#include <stdio.h>
#include <string.h>


int strstrs(char *str1,char *str2)
{
  return (strstr(str1, str2)-str1);
}

void main()
{
    unsigned char str[100] = "https://blog.csdn.net/yuweize";
    unsigned char substr[100] = "yu";
   
    printf("%d\n", strstrs(str,substr));
}

5、输出结果为22,即代"yu"在数值中首次出现的地址为22

 

举报

相关推荐

0 条评论