VC++ mfc在给定字符中,随机生成规定位数的字符串(不重复)
VC++ mfc在给定字符中,随机生成规定位数的字符串(不重复)VC++ MFC可以根据提供的字符生成明文密码,如果不希望生成的随机字符串中出现重复字符,可以在生成随机数时判断是否已经存在于结果字符串中,如果已经存在,则重新生成随机数,直到生成一个未出现过的随机数为止。以下是一个修改后的示例代码:
CString GenerateRandomString(CString strChars, int nLength)
{
CString strResult;
int nCharsLength = strChars.GetLength();
srand((unsigned)time(NULL));
while (strResult.GetLength() < nLength)
{
int nRandomIndex = rand() % nCharsLength;
TCHAR ch = strChars.GetAt(nRandomIndex);
if (strResult.Find(ch) == -1)
{
strResult += ch;
}
}
return strResult;
}在上面的代码中,我们使用了一个 while 循环,每次生成一个随机数,并判断是否已经存在于结果字符串中,如果不存在,则将其拼接到结果字符串中。如果已经存在,则继续生成随机数,直到生成一个未出现过的随机数为止。最后,我们返回生成的字符串。
使用示例:
CString strChars = _T("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
CString strRandom = GenerateRandomString(strChars, 8);
AfxMessageBox(strRandom);
在上面的示例中,我们使用了一个包含数字、大写字母和小写字母的字符集,并生成了一个长度为8的不重复随机字符串。你可以根据需要修改字符集和字符串长度。
页:
[1]