1

As a novice in c++, I try to use it could reverse a string with this

class Solution {
public:
    void reverses(string s,int begin,int end){
        char c;
        for(int i=begin,j=end-1;i<j;i++,j--){  
            c=s[i];  
            std::cout<<s[i]<<std::endl;
            s[i]=s[j];  
            s[j]=c;  
            std::cout<<s[j]<<std::endl;
        }  
    }
    string reverseLeftWords(string s, int n) {
        reverses(s,0,n);
        return s;
    }
};

But it give me the original string. But when i use it in *char `

void Reverse(char *s,int n){  
    for(int i=0,j=n-1;i<j;i++,j--){  
        char c=s[i];  
        s[i]=s[j];  
        s[j]=c;  
    }  
}  

int main()  
{  
    char s[]="hello";  
    Reverse(s,5);
    cout<<s<<endl;
    return 0;
}

it out put olleh, what's different between them?

2
  • en.cppreference.com/w/cpp/algorithm/reverse Commented Apr 23, 2020 at 15:13
  • Also consider std::swap. You should also be careful with const char* string literals. I would expect your code to crash on some systems. Commented Apr 25, 2020 at 10:21

2 Answers 2

2

In the second example, you use a pointer to a character, which means that the function is changing the original string data, in place, which works. Contrast this with the first sample, where you pass in a std::string by value (meaning that the function is working on a copy of that string), reverse it in-place, and then discard the result.

If you want to use an std::string you can either take it by reference or by pointer-to-object:

void reverses(string& s,int begin,int end){
        char c;
        for(int i=begin,j=end-1;i<j;i++,j--){  
            c=s[i];  
            std::cout<<s[i]<<std::endl;
            s[i]=s[j];  
            s[j]=c;  
            std::cout<<s[j]<<std::endl;
        }  
    }

or

void reverses(string* s,int begin,int end){
        char c;
        for(int i=begin,j=end-1;i<j;i++,j--){  
            c=(*s)[i];  
            std::cout<<(*s)[i]<<std::endl;
            (*s)[i]=(*s)[j];  
            (*s)[j]=c;  
            std::cout<<(*s)[j]<<std::endl;
        }  
    }

    string reverseLeftWords(string s, int n) {
        reverses(&s,0,n);
        return s;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your detailed explanation and example! It help me so much!
2

You need to pass your string a reference:

void reverses(string& s,int begin,int end){

Or return it as a result

string reverses(string s,int begin,int end){
   ...
   return s;
}

1 Comment

Thanks for you so much! Good to know why it could not work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.