string替换字符串,路径的斜杠替换为下划线

本文详细介绍了如何在C++中使用string类的find和replace函数来替换字符串中的特定字符或子串,包括如何将路径中的特定字符进行全局替换,提供了实用的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景

替换某个路径的所有“\”为“_”。

很多时候取证需要把恶意代码文件取回来,然后清除。

如果在D:\WEB\模板制作插件\需要覆盖\CodeColoring\CodeColoring.xml这样的目录下,我会把路径也一并记录下来。

D_WEB_模板制作插件_需要覆盖_CodeColoring_CodeColoring.xml

技术思路

分别替换掉“:"和“\”就可以了

string::npos

npos 是一个常数,用来表示不存在的位置

find

find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值就一定是npos。

replace

replace(const size_type _Off, // 索引值
const size_type _N0,          // 替换位数
const basic_string& _Right    // 替换的字符串
)

封装替换函数的代码

#include   <string>     
#include   <iostream>     
using   namespace   std;     
string& replace_all(string& str,const string& old_value,const string& new_value)     
{     
    while (true) 
    {
        string::size_type   pos(0);
        if ((pos = str.find(old_value)) != string::npos)
        {
            str.replace(pos, old_value.length(), new_value);
        }
        else
        {
            break;
        }
    }  
    return   str;     
}     
string& replace_all_distinct(string& str,const string& old_value,const string&   new_value)     
{     
    for(string::size_type   pos(0);   pos!=string::npos;   pos+=new_value.length())   {     
        if((pos=str.find(old_value,pos))!=string::npos)     
        {
            str.replace(pos,old_value.length(),new_value);   
        }
        else   
        {
            break;
         }
    }     
    return   str;     
}     

int   main()     
{     
    cout   <<   replace_all(string("12212"),"12","21")   <<   endl;     
    cout   <<   replace_all_distinct(string("12212"),"12","21")   <<   endl;     
}   

  
/* 
输出如下:    
22211    
21221 
*/  

代码

- 声明部分

string & replace_all(string& str, const string& old_value, const string& new_value);
        
- 使用部分

// 替换所有的“\\”变成“_”
string new_file_name = replace_all(new_path_name, "\\", "_");
// 替换所有的“:”变成“_”
new_file_name = replace_all(new_path_name, ":", "_");
    
- 定义部分

string & CMFCClistDlg::replace_all(string & str,const string & old_value,const string & new_value)
{
    // TODO: 在此处插入 return 语句
    while (true) 
    {
        string::size_type   pos(0);
        if ((pos = str.find(old_value)) != string::npos)
        {
            str.replace(pos, old_value.length(), new_value);
        }
        else
        {
            break;
        }
    }
    return   str;
}

参考

string替换所有指定字符串(C++)

https://www.cnblogs.com/catgatp/p/6407783.html

c++中string 的replace用法

https://blog.youkuaiyun.com/yinhe888675/article/details/50920836

C++: string 中find函数的用法以及string::npos的含义

https://blog.youkuaiyun.com/linwh8/article/details/50752733

转载于:https://www.cnblogs.com/17bdw/p/10279565.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值