一、c 字符串替換第n次匹配項
c++的string類型提供了replace函數來進行字符串替換,但是如果需要替換某個匹配項是第n次出現的位置呢?可以通過自己編寫替換函數來實現。思路如下:
1、使用find函數查找第n次匹配項的位置;
int findNth(string& str, const string& pattern, int n){
int pos = -1;
while(n--){
pos = str.find(pattern, pos + 1);
if(pos == string::npos) break;
}
return pos;
}
2、使用replace函數進行替換。
void replaceNth(string& str, const string& pattern, int n, const string& newStr){
int pos = findNth(str, pattern, n);
if(pos != string::npos){
str.replace(pos, pattern.size(), newStr);
}
}
二、c替換字符串中的某個字符
使用replace函數來替換字符串中的某個字符。思路如下:
1、使用find函數查找要替換的字符的位置;
void replaceChar(string& str, char oldChar, char newChar){
int pos = str.find(oldChar);
while(pos != string::npos){
str.replace(pos, 1, 1, newChar);
pos = str.find(oldChar, pos + 1);
}
}
三、c 字符串替換中文數字
使用map來存儲中文數字和對應的阿拉伯數字,然後替換字符串中的中文數字為阿拉伯數字。思路如下:
1、初始化map;
map numMap = {
{"一", 1},
{"二", 2},
{"三", 3},
{"四", 4},
{"五", 5},
{"六", 6},
{"七", 7},
{"八", 8},
{"九", 9}
};
2、遍歷字符串,如果遇到中文數字,使用to_string函數將阿拉伯數字轉為字符串,然後使用replace函數進行替換。
void replaceChineseNum(string& str){
for(auto& num : numMap){
int pos = str.find(num.first);
while(pos != string::npos){
str.replace(pos, num.first.size(), to_string(num.second));
pos = str.find(num.first, pos + 1);
}
}
}
四、字符串替換c語言代碼
當需要將c語言代碼中的某個字符串替換為另一個字符串時,可以使用正則表達式和regex_replace函數。思路如下:
1、使用regex_replace函數進行替換。
void replaceCode(string& code, const string& oldStr, const string& newStr){
regex reg(oldStr);
code = regex_replace(code, reg, newStr);
}
五、c 字符串替換指定
如果需要替換字符串中特定位置的字符,可以直接使用string的[]運算符。思路如下:
void replaceAt(string& str, int index, char newChar){
str[index] = newChar;
}
六、字符串字符替換c語言
使用sstream庫中的stringstream來將數值轉為字符串,然後使用replace函數進行替換。思路如下:
void replaceNum(string& str, int num, const string& newStr){
stringstream ss;
ss << num;
string oldStr = ss.str();
int pos = str.find(oldStr);
if(pos != string::npos){
str.replace(pos, oldStr.size(), newStr);
}
}
七、字符串替換
使用replace函數進行字符串替換。思路如下:
void replaceString(string& str, const string& oldStr, const string& newStr){
int pos = str.find(oldStr);
while(pos != string::npos){
str.replace(pos, oldStr.size(), newStr);
pos = str.find(oldStr, pos + newStr.size());
}
}
八、字符串替換碼
當需要替換字符串中的特定碼時,可以使用stringstream將碼轉為字符串,然後使用replace函數進行替換。思路如下:
void replaceCode(string& str, char code, const string& newStr){
stringstream ss;
ss << code;
string codeStr = ss.str();
int pos = str.find(codeStr);
if(pos != string::npos){
str.replace(pos, codeStr.size(), newStr);
}
}
九、c字符串替換
使用replace函數進行字符串替換。思路如下:
void replaceCString(char* str, const char* oldStr, const char* newStr){
string s(str);
replaceString(s, oldStr, newStr);
strcpy(str, s.c_str());
}
十、字符串替換指定字符
使用replace函數進行字符替換。思路如下:
void replaceChar(string& str, char oldChar, char newChar){
replace(str.begin(), str.end(), oldChar, newChar);
}
原創文章,作者:OELL,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/145005.html
微信掃一掃
支付寶掃一掃