单词替换
- 题目来源:
1111 单词替换
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
char str[101];
while (gets(str)!=NULL) { //此处不能使用scanf,因为scanf当遇到空格就输入结束。具体看王道最后一张
char before[101];
char after[101];
scanf("%s%s", before, after);
string s = str;
string a = before;
string b = after;
int len_a = a.length();
if (len_a==0) {
return 0;
}
int len_b = b.length();
int t = s.find(a, 0); //从位置字符串的0位置开始寻找a字符串
while (t!=string::npos) {
if ((s[t-1]==' '&&s[t+len_a]==' ')||t==0||t==s.length()-len_a) { //注意只有找到的位置处是单词才行,也就是除了第一个单词和最后一个单词外其余的前后都必须为空格
s.erase(t, len_a); //注意string的用法:删除t位置后面len_a个字符
s.insert(t, b); //在t位置之前插入字符串b
t = t+len_b; //该处为了防止被替换的单词和原单词一致,而导致死循环
t = s.find(a, t); //在字符串s的t位置开始往后寻找a字符串
}
else{
t = t+len_a; //当找到a字符串时,若不是一个单词,则跳过这个字符串
t = s.find(a, t);
}
}
printf("%s\n", s.c_str()); //要用到scanf输出string时,需要使用c_str();
getchar(); //注意:用gets循环输入时,循环最后一定要写getchar(),不然在第二次输入时会出错
}
return 0;
}
其他一个很妙的方法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[110][110],find[110],to[110];
int i,j;
while(scanf("%s",word[0])!=EOF)
{
i=1;
while(getchar()!='\n')
scanf("%s",word[i++]); //由于scanf输入时,遇到空格就停止了,所以使用二维数组word[][],把一个一个单词存入word。妙。。。。
scanf("%s",find);
scanf("%s",to);
for(j=0;j<i-1;j++)
{
if(strcmp(word[j],find)==0) //每个单词逐一和待替换的单词对比
printf("%s ",to);
else
printf("%s ",word[j]);
}
if(strcmp(word[j],find)==0)
printf("%s\n",to);
else
printf("%s\n",word[j]);
}
return 0;
}