【厚积薄发系列】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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值