
字符串是一组字符。它们也可以被描述为字符数组。一个数组字符可以被看作字符串,每个字符串都有一组索引和值字符串中两个指定索引处的字符切换是我们的修改之一有时候可以使字符串发生变化。在本文中,我们将看到如何交换两个字符在一个使用C++从给定的两个索引中提取字符串。
语法
char temp = String_variable[ ]String_variable[ ] = String_variable[ ]String_variable[ ] = temp
使用索引,我们可以访问 C++ 中字符串中的字符。替换其中的一个字符在某个索引处与另一个字符不同的情况下,我们只需将新字符分配给该位置位置如语法所示。与此类似,交流也发生了。我们是替换前两个字符,将temp添加到第一个位置,然后复制a从第一个索引到名为temp的变量的字符。让我们看一下算法来帮助我们理解。
算法
取字符串 s,两个索引 i 和 j如果索引i和j都是正数,并且它们的值不超过字符串的大小,则临时 := s[ i ]i>s[ i ] = s[ j ]i>s[ j ] = 温度返回否则返回 s 而不做任何更改end if
示例
#include using namespace std;string solve( string s, int ind_first, int ind_second){ if( (ind_first >= 0 && ind_first = 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 swappingSwap the 6th character and the 12th character.Updated String: A stricg to nheck character swappingGiven String: A B C D E F G HSwap the 4th character and the 10th character.Updated String: A B F D E C G H
结论
在C++中,替换给定索引处的字符相当简单。这种方法也允许字符切换。我们可以直接改变 C++ 字符串,因为它们是多变。字符串在其他几种编程语言中是不可变的,例如爪哇。无法分配新字符来替换已有字符。在这些根据情况,必须创建一个新的字符串。如果我们将字符串定义为字符指针,就像这样C、类似的事情也会发生。我们在这个例子中构建了一个函数来交换两个从某个索引点开始的字符。如果满足以下条件,该字符串将被返回且保持不变:从特定索引点开始的字符。如果字符串将返回并保持不变指定的索引超出范围。
以上就是C++程序交换一对字符的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444969.html
微信扫一扫
支付宝扫一扫