16

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!

MSalters
  • 173,980
  • 10
  • 155
  • 350
RnD
  • 1,019
  • 5
  • 23
  • 49
  • 2
    https://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx – FailedDev Nov 19 '11 at 17:58
  • 1
    If your question is deeper than the two answers, then you need to expand on it to tell us what you're really asking? – Mordachai Nov 19 '11 at 18:00

4 Answers4

41

Sure:

#include <string>
#include <algorithm>

std::string s = "03/02";
std::swap(s[1], s[4]);
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
4
std::swap(str[1], str[4]);

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
4

There is. :)

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

Paul Manta
  • 30,618
  • 31
  • 128
  • 208
0

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);
}
Mahmoud Al-Qudsi
  • 28,357
  • 12
  • 85
  • 125
  • but it did answer my question and now I know how to solve the whole exercise :D – RnD Nov 19 '11 at 18:13