本文介绍: 函数strStr()

实例要求:

  • 1、请你实现C库函数strstr()stdio.h & string.h),请在 haystack 字符串中找出 needle 字符串第一个匹配项的下标(下标从 0 开始);
  • 2、函数声明:int strStr(char* haystack, char* needle);
  • 参数:
  • 1、haystack –> 被检索的字符串
  • 2、needle –> haystack字符串内要匹配的子字符串
  • 返回值:
  • 1、函数strStr()返回在 haystack中第一次出现 needle 字符串的位置
  • 2、在 haystack中未找到则返回-1

案例展示:

在这里插入图片描述

实例分析:

  • 1、利用strlen函数分别求出字符串haystack和needle的长度
  • 2、双重for嵌套循环遍历两个字符串
  • 3、设置标志位flag初值为0
  • 4、当flag等于0时,返回第一个匹配项的下标
  • 5、其他的情况则返回-1

示例代码:

	int strStr(char* haystack, char* needle) {
	
	    int len1 = strlen(haystack);
	    int len2 = strlen(needle);
	
	    int i = 0;
	    int j = 0;
	
	    int flag = 0;
	
	    for(i = 0; i < len1; i++)
	    {
	        flag = 0;
	        for(j = 0; j < len2; j++)
	        {
	            if(haystack[i+j] != needle[j])
	            {
	                flag = 1;
	                break;
	            }
	 
	        }
	        if(flag == 0)
	        {
	            return i;
	        }
	    }
	
	    return -1;
	   
	}
    

运行结果:

在这里插入图片描述
在这里插入图片描述

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注