c++

c++ replace函数能替换所有匹配项吗

小樊
85
2024-06-25 16:21:26
栏目: 编程语言

c++中的replace函数是用于替换指定位置的元素,而不是替换所有匹配项。replace函数的原型如下:

void replace (const_iterator first, const_iterator last, InputIterator first2, InputIterator last2);

其中,firstlast指定了要替换的元素的范围,first2last2指定了替换元素的范围。

如果要替换所有匹配项,通常需要使用循环结构和find函数来实现。例如,可以使用以下代码来替换字符串中的所有匹配项:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    size_t pos = str.find("l");
    while (pos != std::string::npos) {
        str.replace(pos, 1, "X");
        pos = str.find("l", pos + 1);
    }
    
    std::cout << str << std::endl;
    
    return 0;
}

上述代码会将字符串中的所有字符'l'替换为'X'

0
看了该问题的人还看了