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

来源:互联网 发布:qq手机壁纸软件 编辑:程序博客网 时间:2024/05/21 20:24
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000

int getlines(char line[],int max);
int strindex(char source[],char searchfor[]);

char pattern[] = "ould";  /*pattern to search for */

/*find all lines matching pattern */
int main(void)
{
   char line[MAXLINE];
   int k;
   int found = 0;


   while(getlines(line,MAXLINE) > 0){
       if((k = strindex(line,pattern)) >= 0)

       {  

          printf("%s\n%d\n",line,k);

          for(; line[k] != '\0';k++)
             printf("%c",line[k]);
     found++;
       }
       else
        printf("%d\n",k);
   }
   return found;
}


int getlines(char s[],int lim)
{
   int i,c;


   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 strindex(char *s,char *t)
{
   int i,j,k;


   for(i = strlen(s) - 1; i >= 0; i--){
       for(j = i,k = strlen(t)-1; k >= 0 && s[j] == t[k];k--,j--)
     ;
  if(k < 0)
          return (j+1);
   }
   return -1;
}

阅读全文
0 0
原创粉丝点击