需要帮助理解一个循环的单词

Need help understanding a word jumble for loop

本文关键字:一个 循环 单词 帮助 助理      更新时间:2023-10-16

此代码是杂乱无章的程序的一部分。我需要帮助了解for循环的工作方式并创建混乱的单词。例如,如果word ="苹果",输出将类似于:PLPEA。所以我想知道for循环中发生了什么以使此输出发生。

    std::string jumble = theWord;
    int length = theWord.size();
    for (int i = 0; i < length; i++)
    {
        int index1 = (rand() % length);
        int index2 = (rand() % length);
        char temp = jumble[index1];
        jumble[index1] = jumble[index2];
        jumble[index2] = temp;
    }
    std::cout << jumble << std::endl;

我将在for循环的每一行上添加注释:

for (int i = 0; i < length; i++) // basic for loop syntax. It will execute the same number of times as there are characters in the string
{
    int index1 = (rand() % length); // get a random index that is 0 to the length of the string
    int index2 = (rand() % length); // Does the same thing, gets a random index
    char temp = jumble[index1]; // Gets the character at the random index
    jumble[index1] = jumble[index2]; // set the value at the first index to the value at the second
    jumble[index2] = temp; // set the value at the second index to the vaue of the first
    // The last three lines switch two characters
}

您可以这样考虑:对于字符串中的每个字符,在字符串中切换两个字符。同样,%(或模量运算符)只是让剩余的了解模量运算符%

也必须了解mystring [index]将返回该索引的任何角色。例如:" Hello World" [1] ==" E"