-2

I am currently stuck with a slight problem where I want to swap contents in a std::string.

#include <iostream>
#include <string>

void swap(char* t1, char* t2);    // function parameter is wrong syntax
int main(){
    std::string message = "ABC";
    swap(message[0], message[1]); // parameter probably wrong here
    return 0;
}



void swap(char * t1, char * t2){
 return; 
}

GOAL: I wish to do a simple swap of the contents in index 0 and 1 such that after swapping it, the message "ABC" becomes "BAC". As you can see, I tried doing it like I was using a normal array, but it seems this logic doesn't work with strings. I understand that if I switch to

char a[] = "ABC";

it would work, but I wanna try it using the string class.

Belphegor
  • 1,683
  • 4
  • 23
  • 44

2 Answers2

8

The type of message[n] is char. So the signature of your swap function should be

swap(char& a, char& b);

But you should use std::swap instead.

#include <iostream>
#include <string>
#include <utility>

int main(){
    std::string message = "ABC";
    std::swap(message[0], message[1]);
    std::cout << message << std::endl;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

Try the following

#include <iostream>
#include <string>

void swap( char *c1, char *c2 )
{
    char tmp = *c1;
    *c1 = *c2;
    *c2 = tmp;
}

void swap( char &c1, char &c2 )
{
    char tmp = c1;
    c1 = c2;
    c2 = tmp;
}

int main()
{
    std::string message = "ABC";

    swap( message[0], message[1] );
    swap( &message[1], &message[2] );

    return 0;
}

If you want to use standard utilities then the program above can look the following way

#include <iostream>
#include <string>
#include <utility>    

int main()
{
    std::string message = "ABC";

    std::swap( message[0], message[1] );
    message[1] = std::exchange( message[2], message[1] );

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335