溫馨提示×

c++ string庫函數中替換字符串的方法

c++
小樊
570
2024-09-24 22:21:16
欄目: 編程語言

在C++的<string>庫中,你可以使用std::string類的成員函數replace()來替換字符串中的部分內容。

以下是replace()函數的基本語法:

std::string& replace(size_type pos, size_type count, const std::string& str);

參數說明:

  • pos:指定要開始進行替換的位置。
  • count:指定要替換的字符數。如果count為0,則替換從pos開始的所有字符,直到字符串的末尾。
  • str:指定要替換的字符序列。

返回值:

  • 函數返回一個對原字符串的引用,即修改后的字符串。

下面是一個使用replace()函數的示例:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::cout << "Original string: "<< s << std::endl;

    // 替換字符串中的"World"為"C++"
    s.replace(7, 5, "C++");
    std::cout << "Modified string: "<< s << std::endl;

    return 0;
}

輸出:

Original string: Hello, World!
Modified string: Hello, C++!

在這個示例中,我們首先創建了一個包含"Hello, World!“的字符串s。然后,我們使用replace()函數將字符串中的"World"替換為"C++”,并輸出修改后的字符串。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女