简体   繁体   中英

Create random string that includes spaces (one space between characters), and first character is not a space

I have a method that creates a random string that includes spaces with a user-specified length. The problem is, is that sometimes it inserts spaces at the beginning of the string, and it creates consecutive spaces. How do I combat this so my string never has any spaces in the first character but still can have spaces at other indexes (non-consecutive). Keep in mind that I want to be exact with the sizeOfString parameter, so I need the end result to still be a user-specified amount of characters

This is my method:

    public static string CreateRandomString(int sizeOfString)
    {
        const string chars = "A b  C  D  e  F  g  H  I  1  2  3  4  5  6  7  8  ";

        var random = new Random();
        return new string(Enumerable.Repeat(chars, sizeOfString)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }

You could create an infinite sequence of random chars, skip while they are spaces and then take the number of characters you want.

If you declare a new random within your function, then if you call the function too frequently your random strings get repeated.

Also, the frequency of spaces is very high as more than half of your characters are spaces, you could use chars = " AbCDeFgHI12345678" to alleviate this.

private static Random random = new Random();

public static string CreateRandomString(int sizeOfString)
{
    const string chars = "A b  C  D  e  F  g  H  I  1  2  3  4  5  6  7  8  ";

    var randomChars =
        InitInfinite(() => chars[random.Next(chars.Length)])
            .SkipWhile(c => c == ' ')
            .Take(sizeOfString);

    return new string(randomChars.ToArray());
}

public static IEnumerable<T> InitInfinite<T>(Func<T> selector)
{
    while (true)
    {
        yield return selector();
    }
}

Edit - And here's version 2 (final version):

public static string CreateRandomSentence(int sizeOfString)
{
    var sb = new StringBuilder();

    while (sb.Length < sizeOfString)
    {
        int wordLength = random.Next(8) + 1;
        sb.Append(CreateRandomString(wordLength)).Append(" ");
    }

    sb.Length = sizeOfString;

    return sb.ToString();
}

public static string CreateRandomString(int sizeOfString)
{
    const string chars = "AbCDeFgHI12345678";

    var randomChars =
        InitInfinite(() => chars[random.Next(chars.Length)])
            .SkipWhile(c => c == ' ')
            .Take(sizeOfString);

    return new string(randomChars.ToArray());
}

public static IEnumerable<T> InitInfinite<T>(Func<T> selector)
{
    while (true)
    {
        yield return selector();
    }
}

private static Random random = new Random();

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