【厚积薄发系列】C++项目总结8—全自动和半自动随机生成中文字符串

需求背景:
最近数据库相关的代码,功能类似会员数据。代码写完后,需要模拟数据测试接口,其中一个字段就是用户姓名,需要模拟中文的用户名,所以就有了下面的随机生成中文的代码。

具体实现:

#include "stdafx.h"

#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
class RandCommon
{
public:
//全自动随机  n_count想生成汉字的个数
static void get_rand_chinese_char(const int n_count, std::string& str_content);
//半自动随机 (自己配置字库集合)
static void get_half_rand_chines_char(std::string& str_content);
};

void RandCommon::get_rand_chinese_char(const int n_count, std::string& str_content)
{
srand(time(NULL));
int n_high = 0xd7 - 0xc1; 
int n_low= 0xfe - 0xa1;
char c_name[3]; 
c_name[2]='\0'; 
for (int i = 0; i < n_count; ++i)

c_name[0]=rand()%n_high + 0xc1;
c_name[1]=rand()%n_low + 0xa1; 
str_content += c_name;
}
}


void RandCommon::get_half_rand_chines_char(std::string& str_content)
{
srand(time(NULL));
//自己配置集合,随机选中集合中的中文字符串
char char_set[6][10] = {"张无忌", "杨过", "张三丰", "郭靖", "萧峰", "段誉"};
int n_count = sizeof(char_set)/sizeof(char_set[0]);
str_content = char_set[rand()%6];
}

int _tmain(int argc, _TCHAR* argv[])
{
std::string str;
RandCommon::get_rand_chinese_char(5, str);
cout << str.c_str() << endl;
RandCommon::get_half_rand_chines_char(str);
cout << str.c_str() << endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/lujiang0120/article/details/80500596