21xrx.com
2024-09-20 05:39:08 Friday
登录
文章检索 我的文章 写文章
C++如何交换两个字符串?
2023-07-10 14:59:25 深夜i     --     --
C++ 交换 字符串

在C++中,交换两个字符串的方法有很多种,包括使用STL库中的swap函数、手动交换两个字符串的值、使用指针交换两个字符串的地址等等。

1. 使用STL库中的swap函数

STL中的swap函数可以交换两个变量的值,其原型如下:


template<class T> void swap(T& a, T& b);

可以看出,只要将两个字符串作为参数传入即可完成交换。

示例代码如下:


#include<iostream>

#include<algorithm>

using namespace std;

int main()

{

  string str1 = "hello", str2 = "world";

  cout << "初始值: " << str1 << " " << str2 << endl;

  swap(str1, str2);

  cout << "交换后: " << str1 << " " << str2 << endl;

  return 0;

}

输出结果:


初始值: hello world

交换后: world hello

2. 手动交换两个字符串的值

手动交换两个字符串的值也是一种常见的方法,其原理是先用一个临时变量存储其中一个字符串的值,然后将该字符串的值替换为另一个字符串的值,最后将另一个字符串的值替换为临时变量的值。

示例代码如下:


#include<iostream>

using namespace std;

int main()

str2 = "world";

  cout << "初始值: " << str1 << " " << str2 << endl;

  string temp = str1;

  str1 = str2;

  str2 = temp;

  cout << "交换后: " << str1 << " " << str2 << endl;

  return 0;

输出结果同样为:


初始值: hello world

交换后: world hello

3. 使用指针交换两个字符串的地址

还有一种方法是使用指针,将两个字符串的地址交换。具体做法是先定义两个指向字符串的指针,然后分别将它们指向两个字符串,最后交换它们的指针值。

示例代码如下:


#include<iostream>

using namespace std;

int main()

{

  string str1 = "hello", str2 = "world";

  cout << "初始值: " << str1 << " " << str2 << endl;

  string *p1 = &str1, *p2 = &str2;

  swap(p1, p2);

  cout << "交换后: " << *p1 << " " << *p2 << endl;

  return 0;

}

输出结果同样为:


初始值: hello world

交换后: world hello

综上所述,C++中交换两个字符串有多种方法,可以根据具体情况选择适合的方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复