卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章19499本站已运行343

C++程序交换一对字符

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、类似的事情也会发生。我们在这个例子中构建了一个函数来交换两个 从某个索引点开始的字符。如果满足以下条件,该字符串将被返回且保持不变: 从特定索引点开始的字符。如果字符串将返回并保持不变 指定的索引超出范围。

卓越飞翔博客
上一篇: 掌握PHP8底层开发原理解析与新特性应用示例
下一篇: 返回列表

相关推荐

留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏