张云聪
原题链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=39
问题分析:找到对应的字符串,然后进行替换。
不用c++中string类代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <stack> #include <map> #include <string> #include <algorithm> #define MAX 1000 using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { char input[MAX]; while(gets(input)){ char output[MAX]; int size=0; int length=strlen(input); for(int i=0;i<length;i++){ if(input[i] == 'y' && input[i+1] == 'o' && input[i+2] == 'u'){ output[size++]='w'; output[size++]='e'; i=i+2; } else { output[size++] = input[i]; } } for(int i=0;i<size;i++){ cout<<output[i]; } cout<<endl; } return 0; }优秀代码: 01. #include<algorithm> 02. #include<iostream> 03. #include<string> 04. 05. using namespace std; 06. 07. int main() 08. { 09. string s, s1, s2; 10. while(getline(cin,s)) 11. { 12. int flag; 13. s1 = "you"; 14. s2 = "we"; 15. flag = s.find(s1,0); 16. while(flag != string::npos) 17. { 18. s.replace(flag, 3, s2); 19. flag = s.find(s1, flag + 1); 20. } 21. cout << s << endl; 22. } 23. return 0; 24. } 代码分析:不用c++中string类是因为想用c语言来实现主要逻辑,但c中string.h库中的函数不是很清楚,所以就自己写了查找的函数。自己的代码中其实不需要遍历到length-1,you是3个字符,因此遍历到length-3即可结束遍历.优秀代码主要用了string中的两个函数:find()和replace()。
find(要查找的字符串,查找开始位置);
replace(代替的位置,代替的长度,代替的字符串)