简体   繁体   English

为什么我的代码不反转 c++ 中的字符串?

[英]Why doesn't my code reverse string in c++?

As a novice in c++, I try to use it could reverse a string with this作为c++的新手,我尝试使用它可以反转一个字符串

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 `但是当我在 *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?它输出 olleh,它们之间有什么不同?

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.在第二个示例中,您使用了一个指向字符的指针,这意味着 function 正在更改原始字符串数据,这是有效的。 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.将此与第一个示例进行对比,在第一个示例中,您按值传入std::string (意味着 function 正在处理该字符串的副本),就地反转它,然后丢弃结果。

If you want to use an std::string you can either take it by reference or by pointer-to-object:如果你想使用std::string ,你可以通过引用或指向对象的指针来获取它:

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;
    }

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM