swapping letters in a string

Hi. Yesterday i did a code which swaps the letters that are next to each other in a string. For an example:

input="lalala", output="alalal". or input "bark", output = "arkb".
"b" is next to "a" and we swap. Now "b" is next to "r" and we swap again. And so on..

Today i tried doing it again, but without loops and in a "void(char* x)" function.
I'm really messed up and i'm trying to figure out how i can express the replacement in the function. I know it's something like :
temp=str1; str1=str2; str2=temp;
But i have no clue how i can express it in this case. And also i used a recursion:
"replace(str+1)", so i can have the next letter in the string. But is it okey?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>

using namespace std;
void replacee(char* str)
{
char temp[4];

//here the replacement with the "temp"?

if (*str!='\0'){
    replacee(str+1); // do i need a ",(str+2)" as well?
    }
    cout << str;
}
int main()
{
    char str[4];
    cin >> str;

    replacee(str);
    cout << endl;
    return 0;
}
Hi a bit confused! Do you want to basically place the beginning letter at the end of the original word? Taking your example: "bark" do you wish to output "arkb"? Do you want to use recursion to swap the starting letter with the second, the now second with the third and so on?
To begin with, your buffer is not large enough to hold a 4 character string, so if you input one 4 characters or more then you have undefined behavior. Always limit your input to the size of the buffer (or use a std::string.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iomanip>
#include <iostream>
#include <utility> 

using namespace std;

// If std::swap is off limits
// void swap(char& a, char& b)
// {
//     char temp = a;
//     a = b;
//     b = temp;
// }

void replacee(char* str)
{
    if (*str && *(str + 1))
    {
        swap(*str, *(str + 1));
        replacee(str + 1);
    }
}

int main()
{
    const size_t bufSize = 64;
    char buffer[bufSize];

    std::cin >> std::setw(bufSize) >> buffer; 
    replacee(buffer);

    cout << buffer << '\n';
}


Topic archived. No new replies allowed.