簡體   English   中英

需要幫助理解一個單詞混雜循環

[英]Need help understanding a word jumble 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;

我將在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”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM