2012-09-11 62 views
0

可能重複:
Unique random string generation生成唯一字符串幸運數字

我不得不產生一個隨機的唯一的字符串。這樣做的目的是在表格中每次成功輸入後生成一個幸運號碼

我不喜歡使用GUID,因爲它在中間是破折號( - )。 Here is an example但它也似乎太長。

我想生成一個大約有10個字符的字符串。

任何好的想法將非常感激。 乾杯

+0

是的,我能做到that..but仍然是這個目的太長時間。 – kandroid

+2

「似乎太長」不是發表另一個問題的理由。 –

+0

這是什麼東西? http://stackoverflow.com/questions/1122483/c-sharp-random-string-generator –

回答

2

您可以創建一個GUID的字符串表示不含破折號:

Guid.NewGuid().ToString("N"); 

誠然,這是32個字符,而不是10,但它是一個簡單而快速的解決方案。

+0

+1,我不知道 – smartcaveman

+0

他們當然很無聊的十六進制數字。而3.2倍太長,更無聊。 –

+0

有時候「無聊」是最好的解決方案。 –

0

你可以試試這個:

public struct ShortGuid 
{ 
    private Guid _underlyingGuid; 

    public ShortGuid(Guid underlyingGuid) : this() 
    { 
     _underlyingGuid = underlyingGuid; 
    } 

    public static ShortGuid Empty 
    { 
     get { return ConvertGuidToShortGuid(Guid.Empty); } 
    } 

    public static ShortGuid NewShortGuid() 
    { 
     return ConvertGuidToShortGuid(Guid.NewGuid()); 
    } 

    private static ShortGuid ConvertGuidToShortGuid(Guid guid) 
    { 
     return new ShortGuid(guid); 
    } 

    public override string ToString() 
    { 
     return Convert.ToBase64String(_underlyingGuid.ToByteArray()).EscapeNonCharAndNonDigitSymbols(); 
    } 

    public bool Equals(ShortGuid other) 
    { 
     return other._underlyingGuid.Equals(_underlyingGuid); 
    } 

    public override bool Equals(object obj) 
    { 
     if (ReferenceEquals(null, obj)) return false; 
     if (obj.GetType() != typeof (ShortGuid)) return false; 
     return Equals((ShortGuid) obj); 
    } 

    public override int GetHashCode() 
    { 
     return _underlyingGuid.GetHashCode(); 
    } 
} 

其中EscapeNonCharAndNonDigitSymbols是一個擴展方法:

public static string EscapeNonCharAndNonDigitSymbols(this string str) 
    { 
     if (str == null) 
      throw new NullReferenceException(); 
     var chars = new List<char>(str.ToCharArray()); 

     for (int i = str.Length-1; i>=0; i--) 
     { 
      if (!Char.IsLetterOrDigit(chars[i])) 
       chars.RemoveAt(i); 
     } 
     return new String(chars.ToArray()); 
    } 
+0

這一個會給你18個字符,如:0ULpP0HECPquj8TtGA –

0

就在昨天不得不做相同的任務。在這裏你去:

public static class RandomStringService 
{ 
    //Generate new random every time used. Must sit outside of the function, as static, otherwise there would be no randomness. 
    private static readonly Random Rand = new Random((int)DateTime.Now.Ticks); 


    /// <summary> 
    /// Create random unique string- checking against a table 
    /// </summary> 
    /// <returns>Random string of defined length</returns> 
    public static String GenerateUniqueRandomString(int length) 
    { 
     //check if the string is unique in Barcode table. 
     String newCode; 
     do 
     { 
      newCode = GenerateRandomString(length); 

     // and check if there is no duplicates, regenerate the code again. 
     } while (_tableRepository.AllRecords.Any(l => l.UniqueString == newCode)); 

//In my case _tableRepository is injected via DI container and represents a proxy for 
//EntityFramework context. This step is not really necessary, most of the times you can use 
//method below: GenerateRandomString 

     return newCode; 
    } 




    /// <summary> 
    /// Generates the random string of given length. 
    /// String consists of uppercase letters only. 
    /// </summary> 
    /// <param name="size">The required length of the string.</param> 
    /// <returns>String</returns> 
    private static string GenerateRandomString(int size) 
    { 
     StringBuilder builder = new StringBuilder(); 
     char ch; 
     for (int i = 0; i < size; i++) 
     { 
      ch = Convert.ToChar(CreateRandomIntForString()); 
      builder.Append(ch); 
     } 
     return builder.ToString(); 
    } 



    /// <summary> 
    /// Create a random number corresponding to ASCII uppercase or a digit 
    /// </summary> 
    /// <returns>Integer between 48-57 or between 65-90</returns> 
    private static int CreateRandomIntForString() 
    { 
     //ASCII codes 
     //48-57 = digits 
     //65-90 = Uppercase letters 
     //97-122 = lowercase letters 

     int i; 
     do 
     { 
      i = Convert.ToInt32(Rand.Next(48, 90)); 
     } while (i > 57 && i < 65); 

     return i; 
    } 
+0

可能「太長」。 –

+0

毫米?請解釋。你的意思是,它可以用較少的擊鍵來完成?毫無疑問,這是可以的。 – trailmax

0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Security.Cryptography; 

namespace LinqRandomString 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      do 
      { 
       byte[] random = new byte[10000]; 

       using (var rng = RandomNumberGenerator.Create()) 
        rng.GetBytes(random); 


       var q = random 
          .Where(i => (i >= 65 && i <= 90) || (i >= 97 && i <= 122)) // ascii ranges - change to include symbols etc 
          .Take(10) // first 10 
          .Select(i => Convert.ToChar(i)); // convert to a character 

       foreach (var c in q) 
        Console.Write(c); 

      } while (Console.ReadLine() != "exit"); 
     } 
    } 
}