2查找子串(4分)

本文介绍了一个简单的子串查找算法实现,通过字符数组作为函数参数,在输入的字符串中查找指定子串并输出其位置。提供了完整的C语言代码示例及运行结果。
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值