将字符串a交换到C ++中的字符串b

时间:2018-02-13 12:01:40

标签: c++ string swap

将字符串a反向交换为b。 将字符串a交换到C ++中的字符串b

// 1e9 + 5

#include <iostream> 
#include <string>
using namespace std; 


int main ()
{
    string a="Hello,Sir";
    string b="";

    int k=5;
    int last=k; 
    for (int i=0;i<k;i++)
    b[i]=a[last--];

    cout << b;

    return 0; 
}

1 个答案:

答案 0 :(得分:2)

在C ++中,您通常使用std::swap来交换两个对象,例如

std::string a = "Hello", b = "world";
std::swap(a, b);

对于std::string,还有std::basic_string::swap

  

将字符串的内容与其他内容交换。所有迭代器和引用都可能无效。

a.swap(b);