【题目】
给定单个字符串str、from和to,已知from字符串中无重复字符,把str中所有from的子串全部替换成to字符串,对连续出现from的部分要求只替换成一个to字符串,返回最终结果字符串。【举例】
str="123abc",from="abc",to="4567",返回"1234567";
str="123",from="abc",to="4567",返回"123";
str="123abcabc",from="abc",to="X",返回"123X";
【实现】
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string str,from,to;
getline(cin, str);
getline(cin, from);
getline(cin, to);
int match = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == from[match++])
{
if (match == from.size())
{
int len = i;
while (match--)
{
str[len--] = 0;
}
match = 0;
}
}
else
match = 0;
}
string cur = "", res = "";
for (int i = 0; i < str.size(); i++)
{
if (str[i] != 0)
cur = cur + str[i];
if (str[i] == 0&&(i==0||str[i-1]!=0))
{
res = res + cur + to;
cur = "";
}
}
if (!cur.empty())
res = res + cur;
cout << res;
return 0;
}
【知识点】
1、本题是一道比较典型的关于字符串替换类型的,此类题目总体思路是先用一重循环找出原串中需要替换的子串(可以标记一下需要替换的地方,比如这里用0进行标记);其次再用一重循环将原串与需要替换的串复制到一个新串中返回。还有一点使用cur、res、match这三个变量比较巧妙。
2、关于string中的size()和length()函数的区别:从 C++标准库中的string中两者的源代码没有什么区别,length是因为沿用C语言的习惯而保留下来的,string类最初只有length,引入STL之后,为了兼容又加入了size,它是作为STL容器的属性存在的,便于符合STL的接口规则,以便用于STL的算法。
string类的size()/length()方法返回的是字节数,不管是否有汉字。