swap letter in string

may i know how to swap letter in string

str.swap(str2) is swapping whole string ...i wan swap letter oni..can anyone teach me.
1
2
3
4
5
#include <algorithm>
//...
string s1 = "a";
string s2 = "b";
iter_swap( s1.begin(), s2.begin() );


Or even:
1
2
3
4
5
string s1 = "a";
string s2 = "b";
char temp = s1[0];
s1[0] = s2[0];
s2[0] = temp;
Last edited on
hmm..but how if string sl = "ball";
and i want to swap the letter inside that string... i mean "ball" become "allb" or "llba" and so on..almost until find all posibilities..
is it possible to do so.
Last edited on
You can use next_permutation or prev_permutation

http://www.cplusplus.com/reference/algorithm/next_permutation.html
for int it is working great but when i put a string or array, the thing doest work... is it my code is wrong...

// next_permutation
#include <iostream>
#include <algorithm>
#include <conio>
#include <string>
using namespace std;

int main () {

string myints[5];
cout<<"enter a word:";
cin>>myints[5];



cout << "The 3! possible permutations with 3 elements:\n";

sort (myints,myints+3);

do {
cout << myints[0] << " " << myints[1] << " " << myints[2] << endl;
} while ( next_permutation (myints,myints+3) );

getch();
return 0;
}


this one got error..can compile but cant run.
cin >> myints[5]

5 is not an accessible array element. C++ works from a zero base so the largest possible value would be a 4.


oic.. its a new thing for me. thanks alot.. but i still didnt manage to get wat i realy wan. i put 4, but the screen show empty result
Why are you using a string array?
1
2
3
4
5
string myints;//In your code you are using just 1 string, not an array

cin >> myints;// if you want to get spaces use getline(cin,myints)

sort ( myints.begin(), myints.end() );//STL algorithms work with iterators 
Last edited on
Topic archived. No new replies allowed.