寻找子串

中国电信2016年IT研发工程师笔试题 12

给定一个已经排好序的字符串数组,空字符串散布在该数组中,编写一个函数寻找一个 给定字符串的位置。

解法:循环搜索第一个字符,第一个匹配则进行统计个数,当匹配个数等于子串长度时,则可以输出位置。

        用到的知识点:1.指针地址+1,等于地址移动所属字符类型长度,指向下一个字符  2.子串声明时候长度可以不确定,用双引号

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

int findIndex(char* par_str, char* child_str )
{
 short i, j = 0;
 int n = strlen(par_str);
 int c = strlen(child_str);
 char* temp = child_str;
  
 for(i = 0; i < n; i++)
 {
   
  if(*temp == *(par_str + i))
  {
   temp++;
   if( ++j == c)
    return i-j+1;        
  }
  else
    temp = child_str;  
 }
 return -1;
}

int main(void)
{
 char par_arr[] = "abc 123 cxy ppppp";
 char child_str[] = "123";
 int index;
  
 index = findIndex(par_arr, child_str);
  
 printf("index= %d", index);
  
 return 0;
}
原文地址:https://www.cnblogs.com/xiaohaigege/p/5240076.html