概述:是一道简单的模拟题,主要有下面的知识点:
- str的遍历思路:基本上,for(int i=0;i<strname.size();i++)是最常见的遍历思路,对于string,下标仍然是很好用的。
- string的replace函数的知识点。
- 解法二的新造数据的思路。
1语法知识点:replace函数的用法:
用str替换指定字符串从起始位置pos开始长度为len的字符
*string& replace (size_t pos, size_t len, const string& str);注意这里的长度是被替换的长度,这里的str是字符串形式,即" "
*用str替换 迭代器起始位置 和 结束位置 的字符
*string& replace (const_iterator i1, const_iterator i2, const string& str);
*用substr的指定子串(给定起始位置和长度)替换从指定位置上的字符串
*string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
具体的两种解法
解法一:replace函数的应用。写完注意返回值是什么。
class Solution {
public:
string defangIPaddr(string address) {
for(int i=0;i<address.size();i++)
{
if(address[i]=='.')
{
address.replace(i,1,"[.]");
i++;
}
}
return address;
}
};
解法二:再用一个字符串
class Solution {
public:
string defangIPaddr(string address) {
string newstr="";
for(auto ch:address)
{
if(ch=='.')newstr+="[.]";
else newstr.push_back(ch);
}
return newstr;
}
};