题目要求把字符串S中所有A字串换成字串B
/*****
*jimmy or kenthy i do not knwon!!!!
*/
#include <stdio.h> #include <stdlib.h> #include <string.h>
int get_next(char* t,int next[]) { int i = 0; int k = -1; int len = strlen(t); next[0] = k; while(i<len-1) { if( k==-1 || t[i]==t[k] ) { k++; i++; if(t[i] != t[k]) next[i] = k; else next[i] = next[k]; } else k = next[k]; } }
int kmp_find(char* s,char* t) { int i = 0; int j = 0; int len1 = strlen(s); int len2 = strlen(t); int next[len2]; get_next(t,next); while(i<len1 && j<len2) { if( j==-1 || s[i] == t[j]) { i++; j++; } else j = next[j]; } if(j>=len2) return i-len2; else return -1; }
char* substr(char* s,char* a,char* b) { int len = strlen(a); int index = kmp_find(s,a);
//kmp find where is a in s or you can use strstr char* head = s; *(head+index) = '\0'; char* tail = s + index + len;
//把字符串s分为 head a tail三部分 sprintf(s,"%s%s%s",head,b,tail); if(kmp_find(s,a) != -1)//如果替换一个后还含有a继续 return substr(s, a, b); else return s; } int main(int argc, char *argv[]) { char* s = (char*)malloc(100); memset(s,0,100); sprintf(s,"%s",argv[1]); printf("str:%s\n",s); printf("sub:%s by %s\nafter:%s\n",argv[2],argv[3],substr(s, argv[2], argv[3]));
free(s); s=NULL; system("PAUSE"); return 0; }
赠送shell实现
echo "xxxxxx" | sed 's/xxx/xxx/g'
awk -v str="sadsadas" 'BEGIN{gsub(/xxx/,"xxxxx",str);print str}'
vi ed等edit内直接s/xx/xxx/g
玩笑的呵呵...
|