c++11 替换字符串一串字符
时间: 2023-10-25 09:21:54 浏览: 44
在 C++11 中,我们可以使用 `std::regex_replace` 函数来替换字符串中的一串字符。以下是一个示例代码:
```c++
#include <iostream>
#include <regex>
int main() {
std::string str = "Hello, world!";
std::regex pattern("world");
std::string replaceStr = "Alice";
std::string result = std::regex_replace(str, pattern, replaceStr);
std::cout << result << std::endl;
return 0;
}
```
在上面的代码中,我们首先定义了一个字符串 `str`,它包含了一段文本。然后,我们定义了一个正则表达式 `pattern`,用来匹配字符串中的一段文本。接着,我们定义了一个字符串 `replaceStr`,它将被用来替换匹配到的文本。最后,我们使用 `std::regex_replace` 函数来替换字符串中的一段文本,并将替换后的结果存储在 `result` 变量中,最终输出结果为 `"Hello, Alice!"`。
需要注意的是,`std::regex_replace` 函数返回的是一个新的字符串,原有字符串并未被修改。
相关问题
c++11 替换字符串字符
在 C++11 中,可以使用 `std::replace()` 或 `std::replace_if()` 函数来替换字符串中的字符。
以下是使用 `std::replace()` 函数替换字符串中的字符的示例代码:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string str = "Hello, world!";
std::replace(str.begin(), str.end(), 'o', 'x');
std::cout << str << std::endl; // 输出:Hellx, wxrld!
return 0;
}
```
在上面的示例中,`std::replace()` 函数接受三个参数,分别是要替换的字符串的起始迭代器、结束迭代器和要替换的字符。在本例中,我们将字符串中的所有 'o' 替换为 'x'。
如果您只需要替换满足某些条件的字符,可以使用 `std::replace_if()` 函数。以下是一个示例代码:
```cpp
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string str = "Hello, world!";
std::replace_if(str.begin(), str.end(), [](char c){ return c == 'o'; }, 'x');
std::cout << str << std::endl; // 输出:Hellx, wxrld!
return 0;
}
```
在上面的示例中,我们使用了一个 lambda 表达式来指定要替换的字符。在本例中,我们将字符串中的所有 'o' 替换为 'x'。
c++11 替换字符串子串
在 C++11 中可以使用 `std::regex` 和 `std::regex_replace` 函数来替换字符串子串。
示例代码:
```cpp
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string str = "The quick brown fox jumps over the lazy dog.";
std::regex reg("fox");
std::string new_str = std::regex_replace(str, reg, "cat");
std::cout << new_str << std::endl;
return 0;
}
```
输出:
```
The quick brown cat jumps over the lazy dog.
```
在上面的示例中,我们使用 `std::regex` 定义了要替换的字符串子串,然后使用 `std::regex_replace` 函数进行替换。第一个参数是原始字符串,第二个参数是正则表达式,第三个参数是替换后的字符串。