字符串替换
将文章中一些单词替换成另一些单词;
1、先用单模式匹配算法找到该字符串(strstr、find、KMP)
2、进行截取和替换(strcat,strcpy)
下面给出相应实现代码:
#include<iostream> #include<string> #include<string.h> #include<stdio.h> using namespace std ; int main() { int n ; while(cin >> n) { if(n == 0) return 0 ; getchar() ; char s[1000] ; char s1[100][100] ; char s2[100][100] ; for(int i = 0 ; i < n ; i++) { gets(s1[i]) ; gets(s2[i]) ; } gets(s) ; char *p = NULL ; for(int i = 0 ; i < n ; i++) { p = strstr(s,s1[i]) ; if(p != NULL) { int j = 0 ; while(s+j != p) j++ ; s[j] = '\0' ; int len = strlen(s1[i]); char sh[100] ; strcpy(sh,s+j+len) ; strcat(s,s2[i]) ; strcat(s,sh) ; i = -1 ; p = NULL ; } } cout << s << endl ; } return 0 ; }