69,336
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
#define MAXCHAR 1000 /* 最大输入字符 */
int strrindex(char s[],char searchfor[]);
int inputlines(char s[],int lim);
char t[]="ould"; /* 要查找的模式,可修改测试 */
/* 字符串t在s中最后出现的位置,如果s中不包含t,那么返回-1 */
int main()
{
int i=0,len=0,found=0;
char s[MAXCHAR];
for (i=0;i<MAXCHAR;i++)
{
s[i]=0;
}
printf ("input s: (end input on windows:enter,ctrl+z;on linux :enter,ctrl+d)\n");
len=inputlines(s,MAXCHAR);
found=strrindex(s,t);
printf ("find \"%s\" in s,(place begin 0) place is: %d\n",t,found);
return found;
}
/* strrindex函数: 返回字符串t在s中最后出现的位置,如果s中不包含t,那么返回-1。*/
int strrindex(char s[],char t[])
{
int i=0,j=0,place=0;
i=strlen(s);
i--;
while (s[i]!='\0' && i>=0 && place==0)
{ /* 从后往前读取s中的元素 */
j=0;
while (s[i]==t[j] && t[j]!='\0' && s[i]!='\0')
{ /* s中找到t中第一个元素后,s反向变成从前往后比对t中的元素 */
i++;
j++;
}
if (t[j]=='\0')
{ /* t为空或 在s中包含t*/
place=i-j;
}
else
{ /* s中不包含t */
i-=j;
}
i--;
}
if (place==0)
{
place=-1;
}
return place;
}
/* inputlines函数:保存字符数组,返回字符串长度 */
int inputlines(char s[],int lim)
{
int i=0;
int c;
while (i<lim-1 && (c=getchar())!=EOF)
{
s[i]=c;
i++;
}
s[i]='\0';
return i;
}
int strindex(const char * source_buff, const char * searchfor_buff)
{
int pos = (-1) ;
unsigned int source_buff_size = 0, searchfor_buff_size = 0, p = 0;
source_buff_size = strlen(source_buff) * sizeof(char) ;
searchfor_buff_size = strlen(searchfor_buff) * sizeof(char) ;
if(searchfor_buff_size > source_buff_size) { return pos ; }
p = (unsigned int)source_buff + source_buff_size - searchfor_buff_size ;
while(p >= (unsigned int)source_buff )
{
//如果大小写不敏感用memicmp
if( memcmp((void*)p, searchfor_buff, searchfor_buff_size) == 0)
{
pos = p - (unsigned int)source_buff;
break;
}
p--;
}
return pos;
}