温馨提示×

c++ string怎么替换某字符为其他字符

c++
小亿
206
2024-08-17 11:13:34
栏目: 编程语言

要替换C++中的字符串中的某个字符为另一个字符,可以使用std::replace函数。

以下是一个简单的示例代码:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str = "Hello, World!";
    
    // 将字符串中的逗号(,)替换为感叹号(!)
    std::replace(str.begin(), str.end(), ',', '!');

    std::cout << str << std::endl;

    return 0;
}

在上面的示例中,我们使用std::replace函数将字符串str中的逗号,替换为感叹号!。您可以根据需要替换任何字符。

0