简体   繁体   English

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

[英]Need help understanding a word jumble for loop

This code is part of a program that jumbles a word. 这段代码是一个混杂单词的程序的一部分。 I need help understanding how the for loop is working and creating the jumbled word. 我需要帮助来了解for循环的工作方式并创建混乱的单词。 For example if theWord = "apple" the output would be something like: plpea. 例如,如果theWord =“ apple”,输出将类似于:plpea。 So I want to know whats going on in the for loop to make this output. 所以我想知道在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;

I'll add comments on each line of the for loop: 我将在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
}

You can think of it like this: For each character in the string, switch two characters in the string. 您可以这样想:对于字符串中的每个字符,请切换字符串中的两个字符。 Also the % (or the modulus operator) just gets the remainder Understanding The Modulus Operator % 同样,%(或模运算符)也只剩下余数。 了解模运算符%

It's also important to understand that myString[index] will return whatever character is at that index. 同样重要的是要了解myString [index]将返回该索引处的任何字符。 Ex: "Hello world"[1] == "e" 例如:“ Hello world” [1] ==“ e”

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

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