浙江大学 PTA 习题11-6 查找子串 (20 分)

本题要求实现一个字符串查找的简单函数。

函数接口定义:

char *search( char *s, char *t );

函数search在字符串s中查找子串t,返回子串t在s中的首地址。若未找到,则返回NULL。

裁判测试程序样例:

 #include <stdio.h>
    #define MAXS 30

char *search(char *s, char *t);
void ReadString( char s[] ); /* 裁判提供,细节不表 */

int main()
{
    char s[MAXS], t[MAXS], *pos;

    ReadString(s);
    ReadString(t);
    pos = search(s, t);
    if ( pos != NULL )
        printf("%d\n", pos - s);
    else
        printf("-1\n");

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例1:

The C Programming Language
ram

输出样例1:

10

输入样例2:

The C Programming Language
bored

输出样例2:

-1

我的代码

char *search(char *s, char *t)
{
	int i,j;
	char *p=NULL,*q=NULL,*ch;
	ch=s;
	while(*ch++!='\0')	
	{    		
		if(*ch==*t)
		{
			i=0;
			j=0;
			p=ch;
			q=t;
			j=p-s; /*记录匹配开始的位置*/
	    	while(*q!='\0')		
				if(*q++-*p++!=0)  i+=1;	 /*判断不匹配情况*/					
			if(i==0) 
				{ch=p;/*如果有不止一处匹配的情况能用到的*/
				return s+j;
				}
			
		}
		}	
	return NULL;
   }

整体实现,全部代码

#include <stdio.h>
#define MAXS 30

char *search(char *s, char *t);
void ReadString( char s[] ); /* 裁判提供,细节不表 */

int main()
{
    char s[MAXS], t[MAXS], *pos;

    ReadString(s);
    ReadString(t);
    
    pos = search(s, t);
    if ( pos != NULL )
        printf("%d\n", pos - s);
    else
        printf("-1\n");

    return 0;
}
char *search(char *s, char *t)
{
	int i,j;
	char *p=NULL,*q=NULL,*ch;
	ch=s;
	while(*ch++!='\0')	

	{
		
		if(*ch==*t)
		{
			i=0;
			j=0;
			p=ch;
			q=t;
			j=p-s; /*记录匹配开始的位置*/
    	    	while(*q!='\0')		
    				if(*q++-*p++!=0)  i+=1;	 /*判断不匹配情况*/					
    			if(i==0) 
    				{ch=p;/*如果有不止一处匹配的情况能用到的*/
    				return s+j;
    				}		
		}
		}	
	return NULL;
}
void ReadString( char s[] )
{
	gets(s);
} 
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值