我正在尝试将 s1 中的所有字符更改为"x"。但是,当我运行代码时,编译器刚刚打印出"hello world"11次

I'm trying to change all character within s1 to 'x'. When I run the code, however, the compiler just printed out 'hello world' 11 times

本文关键字:代码 运行 编译器 world 11次 hello 打印 但是 s1 字符      更新时间:2023-10-16

我是C++新手。我正在尝试将 s1 中的所有字符更改为"x"。但是,当我运行代码时,编译器刚刚打印出"hello world"11次。为什么会这样?

int main(){
    string s1 = "hello world";
    for (auto &c : s1){
        s1[c] = 'x';
        cout << s1 << endl;
    }

    return 0;
}

在您使用的 for 循环中,c 实际上包含字符串 s1 的不同字符,而不是 s1 中每个元素的索引。

for (auto &c : s1)

要实际更改字符串的每个字符,请使用下面的 for 循环:

for (int c = 0; c < s1.size(); ++c)