标签:io os ar for 代码 on c amp line
k&r习题4-1,返回字符串t在s中最右边出现的位置,我写出了两种解决办法#include<stdio.h> int strrindex(char s[], char t[]) { int i,j,k,m,n; m=strlen(s)-1; n=strlen(t)-1; for(i=m;i>0;i--){ for(j=i,k=n;k>0 && s[j]==t[k];j--,k--) ; if(k==0) return i-n; } return -1; } int strrindex2(char s[], char t[]) { int i,j,k; for(i=strlen(s)-strlen(t);i>=0;i--){ for(j=i,k=0;t[k]!=‘\0‘ && s[j]==t[k];j++,k++) ; if(t[k]==‘\0‘ && k>0) return i; } return -1; }
/* compile with strrindex.c */ #include <stdio.h> #define MAXLINE 100 int my_getline(char line[], int max); int strrindex(char source[], char searchfor[]); int strrindex2(char source[], char searchfor[]); char pattern[]="stupid"; main() { char line[MAXLINE]; int pos=-1; while(my_getline(line,MAXLINE)>0) if((pos=strrindex(line,pattern))>=0){ printf("position is %d\n",pos); }else printf("not find\n"); return 0; } int my_getline(char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != ‘\n‘; ++i) s[i] = c; if (c == ‘\n‘) { s[i] = c; ++i; } s[i] = ‘\0‘; return i; }
标签:io os ar for 代码 on c amp line
原文地址:http://my.oschina.net/sukai/blog/313206