从中文或日文字符集生成随机字符串

时间:2013-09-02 14:50:27

标签: c# java random

我需要生成数百个随机字符串,其中包含中文和日文字符以供测试。是否有任何C#库可以帮助解决这个问题。

更多细节:我找到了一个小工具http://string.uttool.com/default.aspx,它可以从几个预定义的字符集中生成字符串。任何人都知道它是如何工作的,它的生成逻辑是用JS,C#还是用Java编写的?

2 个答案:

答案 0 :(得分:2)

IEnumerable<string> GetRandomStrings(int numberOfExpectedStrings, int minLength, int maxLength, Random randomizer)
{
    var abecedary = new char[] { 'a', 'b' };
    var strings = new List<string>();

    for (int i = 0; i < numberOfExpectedStrings; i++)
    {
        int lengthOfString = randomizer.Next(minLength, maxLength);
        var newString = new StringBuilder(lengthOfString);
        for (int k = 0; k < lengthOfString; k++)
        {
            int randomCharPosition = randomizer.Next(0, abecedary.Length);
            newString.Append(abecedary[randomCharPosition]);
        }
        strings.Add(newString.ToString());
    }

    return strings;
}

将abecedary替换为您选择的中文或日文字符数组。

答案 1 :(得分:2)

要生成字符串,您可以尝试使用此功能:

    private static string GenerateString(int length, int minCharCode, int maxCharCode)
    {
        var builder = new StringBuilder(length);
        var random = new Random();
        for (var i = 0; i < length; i++)
        {
            builder.Append((char) random.Next(minCharCode, maxCharCode));
        }
        return builder.ToString();
    }

minCharCode maxCharCode 设置您的unicode字符范围。您可以将此功能调用数百次。如果您使用可变长度字符串,则可以在每次调用时随机化长度参数。用法:

    static void Main(string[] args)
    {
        const int minJpnCharCode = 0x4e00;
        const int maxJpnCharCode = 0x4f80;
        var random = new Random();
        for (int i = 0; i < 10000; i++)
        {
            Console.WriteLine(GenerateString(random.Next(0, 50), minJpnCharCode, maxJpnCharCode));                
        }
        Console.ReadLine();
    }

<强>更新 中国和日本的字符有很多unicode。您可以从这里Japanese获取它,或者只使用Google。比你需要下一个代码:

    /// <summary>
    /// Represents our characters range
    /// </summary>
    class Range
    {

        public int Begin { get; set; }

        public int End { get; set; }

        public Range(int begin, int end)
        {
            Begin = begin;
            End = end;
        }

    }

我们的发电机:

    private static string GenerateString(int length, IList<Range> ranges) 
    {
        var builder = new StringBuilder(length);
        var random = new Random();
        for (var i = 0; i < length; i++)
        {
            var rangeIndex = random.Next(ranges.Count);
            var range = ranges[rangeIndex];
            builder.Append((char)random.Next(range.Begin, range.End));
        }
        return builder.ToString();
    }

用法:

        var ranges = new[]
        {
            new Range(0x4e00, 0x4f80),
            new Range(0x5000, 0x9fa0),
            new Range(0x3400, 0x4db0),
            new Range(0x30a0, 0x30f0), 
            // and so on.. add any range here
        };
        for (var i = 0; i < 10000; i++)
        {
            Console.WriteLine(GenerateString(random.Next(0, 50), ranges));
        }