C#生成不重復(fù)隨機(jī)字符串類
更新時(shí)間:2015年03月25日 10:46:16 作者:feige
這篇文章主要介紹了C#生成不重復(fù)隨機(jī)字符串類,涉及C#隨機(jī)數(shù)與字符串的操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
本文實(shí)例講述了C#生成不重復(fù)隨機(jī)字符串類。分享給大家供大家參考。具體如下:
這個(gè)C#類用于隨機(jī)產(chǎn)生不重復(fù)的字符串,可以指定字符串范圍,可以指定要產(chǎn)生字符串的長(zhǎng)度
using System;
namespace DotNet.Utilities
{
public class RandomOperate
{
// 一:隨機(jī)生成不重復(fù)數(shù)字字符串
private int rep = 0;
public string GenerateCheckCodeNum(int codeCount)
{
string str = string.Empty;
long num2 = DateTime.Now.Ticks + this.rep;
this.rep++;
Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
for (int i = 0; i < codeCount; i++)
{
int num = random.Next();
str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
}
return str;
}
//方法二:隨機(jī)生成字符串(數(shù)字和字母混和)
public string GenerateCheckCode(int codeCount)
{
string str = string.Empty;
long num2 = DateTime.Now.Ticks + this.rep;
this.rep++;
Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> this.rep)));
for (int i = 0; i < codeCount; i++)
{
char ch;
int num = random.Next();
if ((num % 2) == 0)
{
ch = (char)(0x30 + ((ushort)(num % 10)));
}
else
{
ch = (char)(0x41 + ((ushort)(num % 0x1a)));
}
str = str + ch.ToString();
}
return str;
}
#region
/// <summary>
/// 從字符串里隨機(jī)得到,規(guī)定個(gè)數(shù)的字符串.
/// </summary>
/// <param name="allChar"></param>
/// <param name="CodeCount"></param>
/// <returns></returns>
private string GetRandomCode(string allChar, int CodeCount)
{
//string allChar = "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";
string[] allCharArray = allChar.Split(',');
string RandomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < CodeCount; i++)
{
if (temp != -1)
{
rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(allCharArray.Length - 1);
while (temp == t)
{
t = rand.Next(allCharArray.Length - 1);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
#endregion
}
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:
- C#生成指定范圍內(nèi)的不重復(fù)隨機(jī)數(shù)
- C#生成唯一不重復(fù)訂單號(hào)
- C#隨機(jī)生成不重復(fù)字符串的兩個(gè)不錯(cuò)方法
- C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法
- C#實(shí)現(xiàn)在購物車系統(tǒng)中生成不重復(fù)訂單號(hào)的方法
- c# 兩個(gè)數(shù)組比較,將重復(fù)部分去掉,返回不重復(fù)部分的實(shí)現(xiàn)
- C#實(shí)現(xiàn)排列組合算法完整實(shí)例
- C#中實(shí)現(xiàn)任意List的全組合算法代碼
- C#查找字符串所有排列組合的方法
- C#實(shí)現(xiàn)組合排列的方法
- 詳解C#的排列組合
- C#實(shí)現(xiàn)生成所有不重復(fù)的組合功能示例
相關(guān)文章
C#中高精度計(jì)時(shí)器Stopwatch的用法詳解
偶然發(fā)現(xiàn)C# 的計(jì)時(shí)器類Stopwatch,他特別適合測(cè)量運(yùn)行時(shí)間,使用簡(jiǎn)單、計(jì)時(shí)精確,下面就跟隨小編一起來學(xué)習(xí)一下它的具體應(yīng)用吧2024-11-11
C#自定義函數(shù)NetxtString生成隨機(jī)字符串
這篇文章主要介紹了C#自定義函數(shù)NetxtString生成隨機(jī)字符串,是十分常見的重要功能,需要的朋友可以參考下2014-08-08
C# 4.0 大數(shù)的運(yùn)算--BigInteger的應(yīng)用詳解
本篇文章是對(duì)C# 4.0 大數(shù)的運(yùn)算 BigInteger的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

