简体   繁体   English

C ++字符串-如何用两个字符交换字符串?

[英]C++ string - how to swap a string with two characters?

Given a C++ string, str("ab"), how do I swap the content of str so that it becomes "ba"? 给定一个C ++字符串str(“ ab”),如何交换str的内容,使其变为“ ba”?

Here is my code: 这是我的代码:

string tmpStr("ab");

const char& tmpChar = tmpStr[0];
tmpStr[0] = tmpStr[1];
tmpStr[1] = tmpChar;

Is there a better way? 有没有更好的办法?

Like this: 像这样:

std::swap(tmpStr[0], tmpStr[1]);

std::swap is located in <algorithm> . std::swap位于<algorithm>

If you want a sledgehammer for this nut: 如果您想要用大锤敲打此螺母:

#include <algorithm>
using namespace std;

string value("ab");
reverse(value.begin(), value.end());

This one might be useful for the followup question involving "abc", though swap is preferred for the two-element case. 对于涉及“ abc”的后续问题,此选项可能很有用,尽管对于两个元素的情况,首选swap

Of course, std::swap would be the right thing to do here, as GMan pointed out. 当然,正如GMan指出的那样,std :: swap将是正确的选择。 But let me explain the problem with your code: 但是,让我用您的代码解释问题:

string tmpStr("ab");
const char& tmpChar = tmpStr[0];
tmpStr[0] = tmpStr[1];
tmpStr[1] = tmpChar;

tmpChar is actually a reference to tmpStr[0]. tmpChar实际上是对tmpStr [0]的引用。 So, this is what will happen: 因此,将发生以下情况:

| a | b |  (initial content, tmpChar refers to first character)
| b | b |  (after first assignment)

Note, that since tmpChar refers to the first character, it now evaluates to 'b' and the second assignment does effectivly nothing: 请注意,由于tmpChar指向第一个字符,因此它现在求值为'b',而第二个赋值实际上不执行任何操作:

| b | b |  (after second assignment)

If you remove the & and make tmpChar an actual character variable, it'll work. 如果删除&并使tmpChar成为实际的字符变量,它将起作用。

Look at this :) 看这个 :)

tmpStr[0] ^= tmpStr[1];
tmpStr[1] ^= tmpStr[0];
tmpStr[0] ^= tmpStr[1];

Explanation: 说明:

The XOR operator has the property: (x^y)^y = x
Let's we have a,b:

1 => a^b,b
2 => a^b,b^a^b=a
3 => a^b^a=b,a

The result is b,a.

If you need to get the characters one by one use an revers iterator as shown here 如果你需要一个使用翻领迭代器取得的人物之一如图所示这里

// string::rbegin and string::rend
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str ("now step live...");
  string::reverse_iterator rit;
  for ( rit=str.rbegin() ; rit < str.rend(); rit++ )
    cout << *rit;
  return 0;
}

hth hth

Mario 马里奥

How about: 怎么样:

std::string s("ab");

s[0] = 'b';
s[1] = 'c';

Or 要么

std::string s("ab");

s = std::string("bc");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM