產生隨機字串

來源:互聯網
上載者:User
估摸著以後極有可能使用到,於是寫了一個產生隨機字串的函數。可以自訂建置規則,產生字串長度。模仿了MS的函數風格,建置規則使用宏的或且規則,傳回值使用了布爾型。這裡使用布爾返回可能作用不大。直接貼代碼吧,同樣是兩個檔案。

#pragma once 

#define RdAllType 0x07 //′óD?D′oíêy×?
#define RdNum 0x01 //êy×?
#define RdLowercase 0x02 //D?D′
#define RdUppercase 0x04 //′óD′
static TCHAR szAllChar[] = _T("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");

bool fnRandomString(const int nLeng, TCHAR *RandStringInput, const int nType);




//注釋用了中文,外掛程式粘貼對中文支援不好:

#define RdAllType 0x07 //大小寫和數字
#define RdNum 0x01 //數字
#define RdLowercase 0x02 //小寫
#define RdUppercase 0x04 //大寫
#include "stdafx.h" 
#include "RandomString.h"
#include <stdlib.h>
#include <time.h>

bool fnRandomString(const int nLeng, TCHAR *RandStringInput, const int nType)
{
if (0 == nLeng)
{
return true;
}
if (nLeng < 0)
{
return false;
}

srand((unsigned int)time(NULL));
bool bRet = false;
int nMin = 0;
int nMax = 62;
switch(nType & RdAllType)
{
case RdAllType:
break;
case RdNum:
nMin = 52;
break;
case RdNum | RdLowercase:
nMin = 26;
break;
case RdNum | RdUppercase:
nMin = 26;
break;
case RdUppercase:
nMax = 25;
break;
case RdUppercase | RdLowercase:
nMax = 51;
break;
case RdLowercase:
nMin = 26;
nMax = 51;
break;
default:
return false;
break;
}


int nRange = nMax - nMin;
if (nType == (RdNum | RdUppercase))
{
int nNum = 0;
for (int t = 0; t <= nLeng; t++)
{
nNum = nMin + rand()%nRange;
if (nNum < 52)
{
nNum -= 26;
}
RandStringInput[t] = szAllChar[nNum];
}
}
else
{
for (int t = 0; t <= nLeng; t++)
{
RandStringInput[t] = szAllChar[nMin + rand()%nRange];
}
}

//int tt = 0;
//while (RandStringInput[tt])
//{
// printf("%c ", RandStringInput[tt]);
// tt++;
//}

return true;
}

VS2010下編譯通過。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.