首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

怎么随机产生一个自定义长度的字符串

2013-04-12 
如何随机产生一个自定义长度的字符串?using Systemusing System.Collections.Genericusing System.Linq

如何随机产生一个自定义长度的字符串?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//吴新强于2013年4月10日0:13:19 桂电2507
namespace RandomWord
{
    class Program
    {
        public static char[] chars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'g', 'f', 'h', 'i', 'j', 'k', 'l', 'n', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
        /// <summary>
        /// 主函数
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Console.WriteLine("请输入要生成随机字符串的长度:");
                int length=int.Parse(Console .ReadLine());
                Console.WriteLine("请输入要生成随机字符串的个数:");
                int count = int.Parse(Console.ReadLine());
                Console.WriteLine("请输入分隔符:");
                string separator = (string)Console.ReadLine();
                Console.WriteLine(GetRandomString(length,count,separator));
                Console.ReadKey();


        }
        /// <summary>
        /// 生成随机函数
        /// </summary>
        /// <param name="length"></param>
        /// <param name="count"></param>
        /// <param name="separator"></param>
        static string GetRandomString(int length,int  count, string separator)
        {
            StringBuilder sb=new StringBuilder ();
            Random rd=new Random ();
            for(int i=0;i<count ;i++)
            {
                for(int j=0;j<length;j++)
                {
                    sb .Append (chars[rd .Next(0,chars.Length)]);


                }
                if(i<count -1)
                {
                    sb .Append (separator );


                }
            }
            return  sb .ToString();
        }
    }

}

实验结果:

怎么随机产生一个自定义长度的字符串


热点排行