C++程式:替換特定索引處的字元


字串是由字元組成的集合。我們也可以稱它們為字元陣列。將字元陣列視為字串,字串具有指定的索引和值。有時我們可以對字串進行一些修改,其中一種修改是透過提供特定索引來替換字元。在本文中,我們將瞭解如何使用C++替換字串中特定索引處的字元。

語法

String_variable[ <given index> ] = <new character>

在C++中,我們可以使用索引訪問字串字元。在這裡,要將特定索引處的字元替換為其他字元,我們只需用新字元賦值給該位置,如語法所示。讓我們看看演算法以更好地理解。

演算法

  • 獲取字串s、指定索引i和新字元c
  • 如果索引i為正且其值不超過字串大小,則
    • s[ i ] = c
    • 返回s
  • 否則
    • 返回s,不做任何更改
  • 結束if

示例

#include <iostream>
using namespace std;
string solve( string s, int index, char new_char){
   
   // replace new_char with the existing character at s[index]
   if( index >= 0 && index < s.length() ) {
      s[ index ] = new_char;
      return s;
   } else {
      return s;
   }
}
int main(){
   string s = "This is a sample string.";
   cout << "Given String: " << s << endl;
   cout << "Replace 8th character with X." << endl;
   s = solve( s, 8, 'X' );
   cout << "Updated String: " << s << endl;
   cout << "Replace 12th character with ?." << endl;
   s = solve( s, 12, '?' );
   cout << "Updated String: " << s << endl;
}

輸出

Given String: This is a sample string.
Replace 8th character with X.
Updated String: This is X sample string.
Replace 12th character with ?.
Updated String: This is X sa?ple string.

結論

在C++中,替換指定索引處的字元非常簡單。C++字串是可變的,因此我們可以直接更改它們。在Java等其他語言中,字串是不可變的。無法透過為其分配新字元來替換其中的字元。在這種情況下,需要建立一個新字串。如果我們將字串定義為像C語言中的字元指標,也會發生類似的情況。在本例中,我們定義了一個函式來替換給定索引位置處的字元。如果給定的索引超出範圍,它將返回字串,並且字串將保持不變。

更新於:2022年12月14日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.