标签:
输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。
You want someone to help you You I
I want someone to help you
1 #include <cstdio> 2 #include <cstdlib> 3 #include <string> 4 #include <cstring> 5 #include <algorithm> 6 #include <cmath> 7 #define MAX 102 8 #define inf 1000000009 9 10 char src[100002]; 11 char des[MAX]; 12 char cut[MAX]; 13 char huan[MAX]; 14 15 int main(int argc, char const *argv[]) 16 { 17 18 freopen("input.txt","r",stdin); 19 while(gets(src) != 0) { 20 gets(cut); 21 gets(huan); 22 int i = 0; 23 int t = 0; 24 while(i < strlen(src)) { 25 if(src[i] == cut[0]) { 26 bool isBegin = (i == 0) || (src[i-1] == ‘ ‘); 27 int endB = i+strlen(cut); 28 bool isEnd = (i+strlen(cut) == strlen(src)) || (endB < strlen(src) && src[endB] == ‘ ‘); 29 if(!(isBegin && isEnd)) { 30 des[t++] = src[i]; 31 i++; 32 continue; 33 } 34 bool isFind = true; 35 for(int j = 0; j < strlen(cut) && (i+j < strlen(src)); j++) { 36 if(src[i+j] != cut[j]) { 37 isFind = false; 38 break; 39 } 40 } 41 if(isFind) { 42 i = i + strlen(cut); 43 for(int j = 0; j < strlen(huan); j++) { 44 des[t++] = huan[j]; 45 } 46 } 47 else { 48 des[t++] = src[i]; 49 i++; 50 } 51 } 52 else { 53 des[t++] = src[i]; 54 i++; 55 } 56 } 57 des[t] = ‘\0‘; 58 puts(des); 59 } 60 return 0; 61 }
这题本身不难,但又坑。因为是替换单词,所以你得判断它是不是一个单词再替换
标签:
原文地址:http://www.cnblogs.com/jasonJie/p/5736237.html