字符串是一组字符。它们也可以被描述为字符数组。一个数组 字符可以被看作字符串,每个字符串都有一组索引和值 The switching of characters at two specified indices in a string is one of the modifications we 有时候可以使字符串发生变化。在本文中,我们将看到如何交换两个字符在一个 使用C++从给定的两个索引中提取字符串。
char temp = String_variable[ <first index> ] String_variable[ <first index> ] = String_variable[ <second index> ] String_variable[ <second index> ] = temp
Using indices, we may access the characters in a string in C++. To replace a character in this 在某个索引处与另一个字符不同的情况下,我们只需将新字符分配给该位置 position as shown by the syntax. Similar to this, the exchange also took place. We are 替换前两个字符,将temp添加到第一个位置,然后复制a 从第一个索引到名为temp的变量的字符。让我们看一下算法来帮助我们 理解。
#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++中,替换给定索引处的字符相当简单。这种方法也 allows for character switching. We can directly alter C++ strings because they are changeable. The strings are not mutable in several other programming languages, such as Java. It is not possible to assign a new character to replace one that is already there. In these 根据情况,必须创建一个新的字符串。如果我们将字符串定义为字符指针,就像这样 C, something similar will take place. We have built a function in this example to swap two characters starting at a certain index point. The string will be returned and left unaltered if 从特定索引点开始的字符。如果字符串将返回并保持不变 the specified indices are out of bounds.