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!
Asked
Active
Viewed 7.5k times
16
-
2https://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx – FailedDev Nov 19 '11 at 17:58
-
1If 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 Answers
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
-
@KerrekSB I don't think you'd benefit from move semantics in this case? – Mahmoud Al-Qudsi Nov 19 '11 at 18:22
-
-
@BenjaminLindley: You're right, the interna of swap are unaffected. Let me remove those comments then. Perhaps an rvalue overload could let you swap with a temporary, but that's not relevant to this situation. Cheers. – Kerrek SB Nov 19 '11 at 22:24
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