ArtW
ArtW

Reputation: 63

Add incremental alphabetic & numeric chars to string

I need to a method (or 2?) that add suffixes to a string.

Let's say I have the string "Hello".

If I click option 1 it should create a list of strings such as

Hello a Hello b Hello c

I've got that part covered.

The next option I'd need it to create a list such as

Hello aa Hello ab Hello ac ... Hello ba Hello bb Hello bc and so on....

Also...each option has 2 other options..

Say I want to add suffix 1 as a-z and suffix 2 as 0-9 Then it'd be

Hello a0 Hello a1

Is there anyone that can help me? This is how I do a single letter increment.

  if (ChkSuffix.Checked)
            {
                if (CmbSuffixSingle.Text == @"a - z" && CmbSuffixDouble.Text == "")
                {
                    var p = 'a';

                    for (var i = 0; i <= 25; i++)
                    {
                        var keyword = TxtKeyword.Text + " " + p;
                        terms.Add(keyword);
                        p++;
                        //Console.WriteLine(keyword);
                    }
                }
            }

Upvotes: 2

Views: 440

Answers (1)

Enigmativity
Enigmativity

Reputation: 117057

Try using these extension methods:

public static IEnumerable<string> AppendSuffix(
    this string @this, string dictionary)
{
    return dictionary.Select(x => @this + x);
}

public static IEnumerable<string> AppendSuffix(
    this string @this, string dictionary, int levels)
{
    var r = @this.AppendSuffix(dictionary);
    if (levels > 1)
    {
        r = r.SelectMany(x => x.AppendSuffix(dictionary, levels - 1));
    }
    return r;
}

public static IEnumerable<string> AppendSuffix(
    this IEnumerable<string> @this, string dictionary)
{
    return @this.SelectMany(x => x.AppendSuffix(dictionary));
}

public static IEnumerable<string> AppendSuffix(
    this IEnumerable<string> @this, string dictionary, int levels)
{
    var r = @this.AppendSuffix(dictionary);
    if (levels > 1)
    {
        r = r.SelectMany(x => x.AppendSuffix(dictionary, levels - 1));
    }
    return r;
}

Then call them like this:

"Hello ".AppendSuffix("abc"); // Hello a, Hello b, Hello c
"Hello ".AppendSuffix("abc", 2); // Hello aa to Hello cc
"Hello "
    .AppendSuffix("abc")
    .AppendSuffix("0123456789"); // Hello a0 to Hello c9

Upvotes: 2

Related Questions