QString ResultClient::getRandomString(int nLen) qsrand(QDateTime::currentMSecsSinceEpoch()); const char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int size = sizeof(ch); char* str = new char[nLen + 1]; int num = 0; for (int nIndex = 0; nIndex < nLen; ++nIndex) num = rand() % (size - 1); str[nIndex] = ch[num]; str[nLen] = '\0'; QString res(str); return res;

使用UUID生成 Qt 中,有更简单的生成方式,Qt提供了生成UUID(全球唯一识别码)的接口,因此我们可以生成UUID之后,取UUID中的n位作为随机字符串。

Qt生成的UUID格式:

{00000000-0000-0000-0000-000000000000}

	QString ResultClient::getRandomString(int nLen = 5)
		int nLen = rand() % 10;
		nLen = nLen < 5 ? 5 : nLen;	//随机数取余10可能存在为0的情况,为0时取长度为5
		QString strUUID = QUuid::createUuid().toString().remove("{").remove("}").remove("-");
		return strUUID.right(nLen);
复制代码
  •