【问题标题】:swap string a in place to string b in C++ [closed]在 C++ 中将字符串 a 就地交换为字符串 b [关闭]
【发布时间】:2018-02-13 12:01:40
【问题描述】:

将字符串 a 反向交换为 b。 在 C++ 中将字符串 a 替换为字符串 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; 
}

【问题讨论】:

  • 对不起,什么?
  • 字符串b 为空,因此所有b[i] 都将超出范围。您可能想在使用b 之前尝试resize
  • 错误和崩溃的原因非常明显,但由于这里没有令人信服的问题,我认为没有理由提供答案。

标签: c++ string swap


【解决方案1】:

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

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

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

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

a.swap(b);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多