【问题标题】:C++ string swap character placesC++ 字符串交换字符位置
【发布时间】:2011-11-19 17:55:59
【问题描述】:

有没有办法交换字符串中的字符位置?例如,如果我有"03/02",我需要获得"02/03"。 任何帮助表示赞赏!

【问题讨论】:

标签: c++ string swap


【解决方案1】:

当然:

#include <string>
#include <algorithm>

std::string s = "03/02";
std::swap(s[1], s[4]);

【讨论】:

  • @KerrekSB 在这种情况下,我认为您不会从移动语义中受益?
  • 为什么在参数上使用 move 会更通用?
  • @BenjaminLindley:没错,swap 的内部不受影响。让我删除那些 cmets。也许右值重载可以让您与临时交换,但这与这种情况无关。干杯。
【解决方案2】:
std::swap(str[1], str[4]);

【讨论】:

    【解决方案3】:

    有。 :)

    std::swap(str[i], str[j])

    【讨论】:

      【解决方案4】:

      等等,你真的想要这样一个具体的答案吗?您不在乎字符串是否为 2/3 而不是 02/03?

      #include <string.h>
      #include <iostream>
      
      bool ReverseString(const char *input)
      {
          const char *index = strchr(input, (int) '/');
          if(index == NULL)
              return false;
      
          char *result = new char[strlen(input) + 1];
      
          strcpy(result, index + 1);
          strcat(result, "/");
          strncat(result, input, index - input);
      
          printf("%s\r\n", result);
          delete [] result;
      
          return true;
      }
      
      int main(int argc, char **argv)
      {
          const char *test = "03/02";
          ReverseString(test);
      }
      

      【讨论】:

      • 但它确实回答了我的问题,现在我知道如何解决整个练习:D
      猜你喜欢
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 2017-02-17
      • 1970-01-01
      相关资源
      最近更新 更多