C++ 字符串交换字符位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8196037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:09:18  来源:igfitidea点击:

C++ string swap character places

c++stringswap

提问by RnD

is there a way to swap character places in a string? For example if I have "03/02"I need to get "02/03". Any help is appreciated!

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

回答by Kerrek SB

Sure:

当然:

#include <string>
#include <algorithm>

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

回答by Oliver Charlesworth

std::swap(str[1], str[4]);

回答by Paul Manta

There is. :)

有。:)

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

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

回答by Mahmoud Al-Qudsi

Wait, do you really want such a specific answer? You don't care about if the string is 2/3 instead of 02/03?

等等,你真的想要这样一个具体的答案吗?你不在乎字符串是 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);
}