需要帮助理解一个词jumble for循环

时间:2017-09-28 03:45:00

标签: c++ for-loop

此代码是混淆单词的程序的一部分。我需要帮助了解for循环如何工作并创建混乱的单词。例如,如果theWord =“apple”,输出将类似于: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;

1 个答案:

答案 0 :(得分:0)

我将在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
}

您可以这样想:对于字符串中的每个字符,请在字符串中切换两个字符。 此外,%(或模数运算符)只得到余数Understanding The Modulus Operator %

了解myString [index]将返回该索引处的任何字符也很重要。例如:“Hello world”[1] ==“e”