题目105:单词替换

http://ac.jobdu.com/problem.php?cid=1040&pid=104

1、str1.find(str2,pos);   若循环查找,pos+str2.size(),查找完,跳过当前这个位置再查找

2、str1.replace(pos1,num,str2); 替换位置,替换个数,目标字符串

3、出现TE,因为循环查找处问题

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;

int main()
{
	string s,a,b;
	while (getline(cin,s))
	{
		getline(cin,a);
		getline(cin,b);
        int t=s.find(a,0);
		while (t!=string::npos)
		{
		    int flag=0;
			if (t==0)                                //单词头
			{
				if (t+a.size()==s.size())            //仅有一个单词
				{
                   flag=1;
				}
				else if (s[t+a.size()]==' ')          //多个单词
				{
                   flag=1;
				}
			}
			else if (t+a.size()==s.size())              //单词尾
			{
				if (s[t-1]==' ')
				{
                   flag=1;
				}
			}
			else if (s[t-1]==' '&&s[t+a.size()]==' ')
			{
				flag=1;
			}
            if (flag==1)
            {
				s.replace(t,a.size(),b);        //替换位置,替换个数,目标字符串
            }
			t=s.find(a,t+a.size());     //循环查找,上次查找到位置t处后面a.size()个之后继续查找
		}
		cout<<s<<endl;
	}
	return 0;
}


   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章