Rover12421's Blog

The End.

生成随机字符串

估摸着以后极有可能使用到,于是写了一个生成随机字符串的函数。可以自定义生成规则,生成字符串长度。模仿了MS的函数风格,生成规则使用宏的或且规则,返回值使用了布尔型。这里使用布尔返回可能作用不大。直接贴代码吧,同样是两个文件。

RandomString.h
  1. #pragma once
  2.  
  3. #define RdAllType                    0x07    //′óD?D′oíêy×?
  4. #define RdNum                        0x01    //êy×?
  5. #define RdLowercase            0x02    //D?D′
  6. #define RdUppercase            0x04    //′óD′
  7. static TCHAR szAllChar[] = _T("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
  8.  
  9. bool fnRandomString(const int nLeng, TCHAR *RandStringInput, const int nType);

 

注释用了中文,插件粘贴对中文支持不好:

define RdAllType                    0x07    //大小写和数字

define RdNum                        0x01    //数字

define RdLowercase            0x02    //小写

define RdUppercase            0x04    //大写

RandomString.cpp
  1. #include "stdafx.h"
  2. #include "RandomString.h"
  3. #include
  4. #include
  5.  
  6. bool fnRandomString(const int nLeng, TCHAR *RandStringInput, const int nType)
  7. {
  8.     if (0 == nLeng)
  9.     {
  10.         return true;
  11.     }
  12.     if (nLeng < 0)
  13.     {
  14.         return false;
  15.     }
  16.  
  17.     srand((unsigned int)time(NULL));
  18.     bool bRet = false;
  19.     int nMin = 0;
  20.     int nMax = 62;
  21.     switch(nType & RdAllType)
  22.     {
  23.     case RdAllType:
  24.         break;
  25.     case RdNum:
  26.         nMin = 52;
  27.         break;
  28.     case RdNum | RdLowercase:
  29.         nMin = 26;
  30.         break;
  31.     case RdNum | RdUppercase:
  32.         nMin = 26;
  33.         break;
  34.     case RdUppercase:
  35.         nMax = 25;
  36.         break;
  37.     case RdUppercase | RdLowercase:
  38.         nMax = 51;
  39.         break;
  40.     case RdLowercase:
  41.         nMin = 26;
  42.         nMax = 51;
  43.         break;
  44.     default:
  45.         return false;
  46.         break;
  47.     }
  48.  
  49.  
  50.     int nRange = nMax - nMin;
  51.     if (nType == (RdNum | RdUppercase))
  52.     {
  53.         int nNum = 0;
  54.         for (int t = 0; t <= nLeng; t++)
  55.         {            
  56.             nNum = nMin + rand()%nRange;
  57.             if (nNum < 52)
  58.             {
  59.                 nNum -= 26;
  60.             }
  61.             RandStringInput[t] = szAllChar[nNum];
  62.         }
  63.     }
  64.     else
  65.     {
  66.         for (int t = 0; t <= nLeng; t++)
  67.         {            
  68.             RandStringInput[t] = szAllChar[nMin + rand()%nRange];
  69.         }
  70.     }
  71.  
  72.     //int tt = 0;
  73.     //while (RandStringInput[tt])
  74.     //{
  75.     //    printf("%c ", RandStringInput[tt]);
  76.     //    tt++;
  77.     //}
  78.  
  79.     return true;
  80. }

 

VS2010下编译通过。

Comments