首頁  >  文章  >  後端開發  >  C++程式交換一對字符

C++程式交換一對字符

PHPz
PHPz轉載
2023-09-11 19:13:021057瀏覽

C++程式交換一對字符

字串是一組字元。它們也可以被描述為字元數組。一個數組 字元可以被看作字串,每個字串都有一組索引和值 字串中兩個指定索引處的字元切換是我們的修改之一 有時候可以使字串發生變化。在本文中,我們將看到如何交換兩個字元在一個 使用C 從給定的兩個索引中提取字串。

文法

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

使用索引,我們可以存取 C 中字串中的字元。替換其中的一個字符 在某個索引處與另一個字元不同的情況下,我們只需將新字元指派給該位置 位置如語法所示。與此類似,交流也發生了。我們是 替換前兩個字符,將temp添加到第一個位置,然後複製a 從第一個索引到名為temp的變數的字元。讓我們看一下演算法來幫助我們 理解。

演算法

  • 取字串 s,兩個索引 i 和 j
  • 如果索引i和j都是正數,且它們的值不超過字串的大小,則
    • 暫時 := s[ i ]​​i>
    • s[ i ] = s[ j ]​​i>
    • s[ j ] = 溫度
    • 返回
  • 否則
    • 返回 s 而不做任何更改
  • end 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 字串,因為它們是 多變。字串在其他幾種程式語言中是不可變的,例如 爪哇。無法指派新字元來取代已有字元。在這些 根據情況,必須建立一個新的字串。如果我們將字串定義為字元指針,就像這樣 C、類似的事情也會發生。我們在這個例子中建構了一個函數來交換兩個 從某個索引點開始的字元。如果滿足以下條件,則該字串將被傳回且保持不變: 從特定索引點開始的字元。如果字串將返回並保持不變 指定的索引超出範圍。

以上是C++程式交換一對字符的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除