string替換字符串,路徑的斜杠替換為下划線


場景

替換某個路徑的所有“\”為“_”。

很多時候取證需要把惡意代碼文件取回來,然后清除。

如果在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.csdn.net/yinhe888675/article/details/50920836

C++: string 中find函數的用法以及string::npos的含義

https://blog.csdn.net/linwh8/article/details/50752733


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM