C#: How do i modify this code to split the string with hyphens?
Hello i need some help modifying this code so it splits this string with hyphens:
str开发者_如何学JAVAing KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
I would like to lay it out like this:
1234-1234-1234-1234
with a char length of 4 per segment and max chars about 16
Full Code
private static string GetKey()
{
char[] chars = new char[62];
string KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = KeyString.ToCharArray();
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
byte[] data = new byte[1];
crypto.GetNonZeroBytes(data);
data = new byte[8];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(8);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}
return result.ToString();
}
the code is used for generating random ids
any help would be appreciated
Can't... resist... regex... solution
string KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
Console.WriteLine(
new System.Text.RegularExpressions.Regex(".{4}")
.Replace(KeyString, "$&-").TrimEnd('-'));
outputs
abcd-efgh-ijkl-mnop-qrst-uvwx-yzAB-CDEF-GHIJ-KLMN-OPQR-STUV-WXYZ-1234-5678-90
But yes, if this is a Guid, by all means, use that type.
How about:
StringBuilder result = new StringBuilder();
for (var i = 0; i < data.Length; i++)
{
if (i > 0 && (i % 4) == 0)
result.Append("-");
result.Append(chars[data[i] % (chars.Length - 1)]);
}
result.Length -= 1; // Remove trailing '-'
It might be worthwhile to have a look into Guid, it produces strings in the format xxxxxxxx-xxxx-xxxx-xxxxxxxx (32 chars) if you definitely want 16 chars, you could take some 16 chars in the middle of the 32 generated by Guid.
Guid guid = Guid.NewGuid(); /* f.e.: 0f8fad5b-d9cb-469f-a165-70867728950e */
string randomid = guid.ToString().Substring(4, 19);
精彩评论