如何用c++ string匹配實(shí)現(xiàn)字符串替換

c++
小樊
81
2024-09-25 08:53:14

在 C++ 中,你可以使用 std::string 類的成員函數(shù) find()replace() 來(lái)實(shí)現(xiàn)字符串的查找和替換。下面是一個(gè)簡(jiǎn)單的示例:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    std::string to_find = "World";
    std::string to_replace = "C++";

    size_t pos = str.find(to_find);
    if (pos != std::string::npos) {
        str.replace(pos, to_find.length(), to_replace);
    }

    std::cout << "Original string: " << str << std::endl;
    std::cout << "Modified string: " << str << std::endl;

    return 0;
}

在這個(gè)示例中,我們首先定義了一個(gè)原始字符串 str,以及要查找的子字符串 to_find 和要替換的子字符串 to_replace。然后,我們使用 find() 函數(shù)查找子字符串 to_find 在原始字符串中的位置。如果找到了(即 pos 不等于 std::string::npos),我們就使用 replace() 函數(shù)將子字符串 to_find 替換為子字符串 to_replace

最后,我們輸出原始字符串和修改后的字符串。

0