力扣题解-1108IP地址无效化

 

概述:是一道简单的模拟题,主要有下面的知识点:

  1. str的遍历思路:基本上,for(int i=0;i<strname.size();i++)是最常见的遍历思路,对于string,下标仍然是很好用的。
  2. string的replace函数的知识点。
  3. 解法二的新造数据的思路。

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;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值