简体   繁体   中英

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:

string 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM