【发布时间】:2019-08-10 09:19:19
【问题描述】:
我正在用 CS50 课程问题集 2 学习 C,使用 crypt 函数暴力猜出密码。目前正在编写一个打印所有可能的一定长度的字符串的函数,例如:
aa
ab
...
az
ba
...
zy
zz
为此,我编写了一个相当简单的递归函数:
#include <cs50.h>
#include <stdio.h>
#include <crypt.h>
#include <string.h>
void stringcycler(int n, int passLength, char *pass)
// Scrolls through all lowercase letter combinations for a string of length passLength
// Expects an integer value of the length of the strng as both n and passLength
// Also expects a char* array of length passLength with all chars set to 'a' (and a null character)
{
if(n != 0)
{
for(pass[passLength - n] = 'a'; pass[passLength - n] < 'z'; pass[passLength - n]++)
{
stringcycler(n-1, passLength, pass);
printf("%s\n", pass);
// return 0;
}
}
}
int main()
{
// Initialise char *c, and scroll through letters
int passLength = 2; // The number of characters you want to brute force guess
char pass[passLength + 1]; // Add 1 for the null character
int i;
for(i = 0; i < passLength; i++) pass[i] = 'a'; // Set every char in pass to 'a'
pass[passLength] = '\0'; // Set null character at the end of string
stringcycler(passLength, passLength, pass);
return 0;
}
它在大多数情况下都有效,但只适用于 yz。每当它看到 z 时,它基本上都会跳过,所以它会转到 yz,然后从不会 za 到 zz。如果我在 for 循环行中添加一个 =:
pass[passLength - n] < 'z';
即。
pass[passLength - n] <= 'z';
然后它在混合中打印“{”字符。有什么帮助吗?另一个问题是,我怎样才能改变它以适用于所有大小写组合,有没有一种简洁的方法?
【问题讨论】:
-
有一个cs50 stack exchange site如果你有兴趣。
标签: c string recursion cs50 brute-force