c ++ void函数不改变string的值

时间:2017-07-18 10:24:43

标签: c++ string

我正在尝试解决CTCI上的Q1.3:编写一个方法来用'%20'替换字符串中的所有空格。您可以假设字符串在末尾有足够的空间来容纳附加字符,并且您将获得字符串的“真实”长度。

我在main上运行我的功能并且它可以工作,但是当我通过main传递函数时,我不断获得原始字符串“Mr. John Smith”而不是“Mr%20John%20Smith”。这是我的代码。

int main(int argc, const char * argv[]) {
    string test = "Mr John Smith          ";
    int length = 13;
    URLify(test, length);
    cout << test << endl;
    return 0;
}

void URLify(string a, int length){
    string b = a;
    int counter = 0;
    for(int i=0;i<length;i++){
        if(b[0] != ' '){
            a[counter]= b[0];
            counter++;
        }
        else{
            a[counter] = '%';
            a[counter+1] = '2';
            a[counter+2] = '0';
            counter = counter + 3;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

因为您按价值传递了a ,所以会创建它的副本并 正在修改。通过引用将传递给string& a

答案 1 :(得分:1)

通过引用而不是按值传递。应该是:

void URLify(std::string& a, int length)