Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string swap character places

Tags:

c++

string

swap

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!

like image 333
RnD Avatar asked Nov 19 '11 17:11

RnD


People also ask

How do you interchange characters in a string in C?

For swapping two strings from one location to another location, we use strcpy() function. An array of characters (or) collection of characters is called a string.

How do I swap characters in a string?

As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.

How do I swap char arrays?

str_swap(&char_array[0],&char_array[2]); shouldn't compile, because &char_array[0] and &char_array[2] are not char** s. Swapping char[] is not the same as swapping pointers. If you want to swap pointers, your array needs to contain pointers, not arrays (and your swap function is close to correct, btw).


1 Answers

Sure:

#include <string>
#include <algorithm>

std::string s = "03/02";
std::swap(s[1], s[4]);
like image 92
Kerrek SB Avatar answered Sep 21 '22 20:09

Kerrek SB