C++ string swap character places

你。 提交于 2019-12-12 10:38:47

问题


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!


回答1:


Sure:

#include <string>
#include <algorithm>

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



回答2:


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




回答3:


There is. :)

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




回答4:


Wait, do you really want such a specific answer? You don't care about if the string is 2/3 instead of 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);
}


来源:https://stackoverflow.com/questions/8196037/c-string-swap-character-places

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!