[英]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.