概述:是一道簡單的模擬題,主要有下面的知識點:
- 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;
}
};