2
查找子串(4分)
题目内容:
用字符数组作函数参数,编程实现在从键盘输入的字符串(假设长度小于80)中查找与指定的子串,并输出该子串在字符串中首次出现的位置,如果该字符不存在,则输出"Not found!"。
函数原型:int SearchString(char s[], char d[])
函数功能:在字符数组s中查找子串d,返回d在s中首次出现的位置,若找不到,则返回-1。
程序运行结果示例1:
Input a string:How are you!↙
Input another string:are↙
Searching results:5
程序运行结果示例2:
Input a string:hello↙
Input another string:are↙
Not found!
程序运行结果示例3:
Input a string:You are a student.↙
Input another string:you↙
Not found!
输入第一个字符串的提示信息:"Input a string:"
输入第二个字符串的提示信息:"Input another string:"
输入格式: gets()
输出格式:"Searching results:%d\n"
没找到子串的输出提示信息: "Not found!\n"
注意:为避免出现格式错误,请直接拷贝粘贴上面给出的输入、输出提示信息和格式控制字符串!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int SearchString(char s[], char d[]);
int main()
{
char s[100],d[100];
int jud;
printf("Input a string:");
gets(s);
printf("Input another string:");
gets(d);
jud=SearchString(s,d);
if(jud==-1) printf("Not found!\n");
else printf("Searching results:%d\n",jud);
return 0;
}
int SearchString(char s[], char d[])
{
int i,j,jud=0,a;
int len1=strlen(s),len2=strlen(d);
for(i=0;i<len1;i++)
{
if(s[i]==d[0])
{
for(j=0,a=i;j<len2;j++,a++)
{
if(s[a]==d[j]) jud++;
}
if(jud==len2) return i+1;
else jud=0;
}
}
return -1;
}时间限制:500ms内存限制:32000kb
本文介绍了一个简单的子串查找算法实现,通过字符数组作为函数参数,在输入的字符串中查找指定子串并输出其位置。提供了完整的C语言代码示例及运行结果。
&spm=1001.2101.3001.5002&articleId=80792821&d=1&t=3&u=2fc10380bee1418fadecdc7565dffcb2)
5275

被折叠的 条评论
为什么被折叠?



