`
carolaif
  • 浏览: 71024 次
  • 性别: Icon_minigender_2
  • 来自: 大连
最近访客 更多访客>>
社区版块
存档分类
最新评论

C程序设计语言(第二版) 4-1

阅读更多

4-1  编写函数strrindex(s,t),它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1

 

#include<stdio.h>
#define MAXLINE 100

int getline(char line[], int max);
int strrindex(char s[], char t[]);

char pattern[] = "abc";//要查找的模式

int main()
{
	char line[MAXLINE];
	int found = 0;
	while(getline(line,MAXLINE)>0){
		found = strrindex(line,pattern);
		printf("%s出现在最右边第%d个字符",pattern,found);
	}
	return 0;
}

int getline(char s[],int lim)
{
	int c,i;
	i=0;
	while(--lim>0 && (c=getchar())!=EOF && c!='\n')
		s[i++]=c;
	if (c=='\n')
		s[i++]=c;
	s[i]='\0';
	return i;
}

int strrindex(char s[], char t[])
{
	int i,j,k,right;
	j=0;
	k=0;
	right=0;
	for(i=0;s[i]!='\0';i++){
		for(j=i,k=0; t[k]!='\0' && s[j]==t[k];k++,j++)
			;
		if(k>0 && t[k]=='\0')
		{
			if(i>right)
				right = i;
		}
	}

	if(right==0)
		return -1;
	else 
		return right;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics