码龄10年
暂无认证
43363
访问
1
等级
8
获赞
3
评论
热门文章
-
一.某岛之人物对象及其加密函数解析
2654
-
一.《传奇M》装备栏遍历的突破口
2281
-
二.某龙端游中LUA的分析和调用
2036
-
一.窗口坐标与屏幕坐标
1756
-
一.《轩辕传奇》周围遍历之二叉树
1754
最新评论
-
20240228阿⑤
积分乍获得
-
20231124ziher
666
-
20230909八月老师
什麼時候發佈易語言支持庫呢
一.几种常见的替换字符串方法
Heart
2023-10-04 18:28:39 发布
375
分类专栏: C/C++ 文章标签: 替换字符串
一.使用 STL 的 `replace` 算法来实现字符串的替换的例子:
#include #include
std::string replace(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return str;
}
int main() {
std::string str = "Hello, 迪大学院!";
std::string from = "学院";
std::string to = "逆向学院";
std::string result = replace(str, from, to);
std::cout << result << std::endl;
return 0;
}二.如果要替换字符串中的多个子串,或者要进行更复杂的字符串替换操作,可以使用正则表达式。下面是使用 C++ 的正则表达式库:
#include #include //需要了解正则表达式规则
std::string replace(std::string str, const std::string& pattern, const std::string& to) {
std::regex r(pattern);
return std::regex_replace(str, r, to);
}
int main() {
std::string str = "Hello, World!";
std::string str = "Hello, World!";
std::string result = replace(str, "World", "C++"); // 替换所有的 "World" 为 "C++"
std::cout << result << std::endl; // 输出:Hello, C++!
result = replace(str, "[Ww]orld", "C++"); // 替换所有的 "World" 或 "world" 为 "C++"
std::cout << result << std::endl; // 输出:Hello, C++!
result = replace(str, "[a-zA-Z]+", "C++"); // 替换所有的单词为 "C++"
std::cout << result << std::endl; // 输出:C++, C++!
result = replace(str, "\\b\\w+\\b", "C++"); // 同上
std::cout << result << std::endl; // 输出:C++, C++!
}三.可以使用 C++ 的字符串流(stringstream)来实现字符串的替换。下面是一个例子:
#include #include
std::string replace(std::string str, const std::string& from, const std::string& to) {
std::stringstream ss;
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
ss << str.substr(0, start_pos) << to;
start_pos += from.length();
str = str.substr(start_pos);
}
ss << str;
return ss.str();
}
int main() {
std::string str = "Hello, World!";
std::string from = "World";
std::string to = "C++";
std::string result = replace(str, from, to);
std::cout << result << std::endl; // 输出:Hello, C++!
return 0;
}四.也可以使用字符数组来实现字符串的替换。下面是一个例子:
#include #include
char* replace(char* str, const char* from, const char* to) {
size_t str_len = strlen(str);
size_t from_len = strlen(from);
size_t to_len = strlen(to);
size_t new_len = str_len + to_len - from_len;
char* new_str = new char[new_len + 1];
char* p1 = str;
char* p2 = new_str;
while (*p1) {
if (strncmp(p1, from, from_len) == 0) {//匹配的就替换
strncpy(p2, to, to_len);
p2 += to_len;
p1 += from_len;
} else {
*p2++ = *p1++;//不匹配的就直接拷贝
}
}
*p2 = '\0';
delete[] str;
return new_str;
}
int main() {
char str[] = "Hello, World!";
const char* from ="World";
const char* to = "C++";
char* result = replace(str, from, to);
std::cout << result << std::endl; // 输出:Hello, C++!
delete[] result;
return 0;
}
网友评论
0条评论 0人参与
评论列表
0
0