C++程式交換字元對


字串是一組字元。它們也可以被描述為字元陣列。字元陣列可以被認為是字串,每個字串都有一組索引和值。在字串中交換兩個指定索引處的字元是我們可以對字串進行的一些修改之一。在本文中,我們將瞭解如何使用 C++ 在兩個給定索引處交換字串中的兩個字元。

語法

char temp = String_variable[ <first index> ]
String_variable[ <first index> ] = String_variable[ <second index> ]
String_variable[ <second index> ] = temp

在 C++ 中,我們可以使用索引訪問字串中的字元。在這種情況下,要將某個索引處的字元替換為另一個字元,我們只需將新字元分配給該位置,如語法所示。類似地,交換也發生了。我們替換前兩個字元,將 temp 新增到第一個位置,然後將第一個索引處的字元複製到一個名為 temp 的變數中。讓我們看看演算法來幫助我們理解。

演算法

  • 獲取字串 s,兩個索引 i 和 j
  • 如果索引 i 和 j 都為正且其值不超過字串大小,則
    • temp := s[ i ]
    • s[ i ] = s[ j ]
    • s[ j ] = temp
    • 返回 s
  • 否則
    • 返回 s 而不做任何更改
  • 結束 if

示例

#include <iostream>
using namespace std;
string solve( string s, int ind_first, int ind_second){
   if( (ind_first >= 0 && ind_first < s.length()) && (ind_second >= 0 && ind_second < s.length()) ) {
      char temp = s[ ind_first ];
      s[ ind_first ] = s[ ind_second ];
      s[ ind_second ] = temp;
      return s;
   } else {
      return s;
   }
}
int main(){
   string s = "A string to check character swapping";
   cout << "Given String: " << s << endl;
   cout << "Swap the 6th character and the 12th character." << endl;
   s = solve( s, 6, 12 );
   cout << "\nUpdated String: " << s << endl;
   s = "A B C D E F G H";
   cout << "Given String: " << s << endl;
   cout << "Swap the 4th character and the 10th character." << endl;
   s = solve( s, 4, 10 );
   cout << "Updated String: " << s << endl;
}

輸出

Given String: A string to check character swapping
Swap the 6th character and the 12th character.
Updated String: A stricg to nheck character swapping
Given String: A B C D E F G H
Swap the 4th character and the 10th character.
Updated String: A B F D E C G H

結論

在 C++ 中,在給定索引處替換字元非常簡單。此方法也允許交換字元。我們可以直接修改 C++ 字串,因為它們是可變的。在其他一些程式語言(如 Java)中,字串是不可變的。無法分配一個新字元來替換已經存在的字元。在這種情況下,必須建立一個新的字串。如果我們像在 C 中那樣將字串定義為字元指標,則會發生類似的事情。在本例中,我們建立了一個函式來交換從某個索引點開始的兩個字元。如果指定的索引超出範圍,則字串將被返回並保持不變。

更新於: 2022年12月14日

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

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