【问题标题】:Add incremental alphabetic & numeric chars to string将增量字母和数字字符添加到字符串
【发布时间】:2013-08-28 00:34:43
【问题描述】:

我需要一个为字符串添加后缀的方法(或 2 个?)。

假设我有字符串“Hello”。

如果我点击选项 1,它应该创建一个字符串列表,例如

你好 你好乙 你好c

我已经涵盖了那部分。

下一个选项我需要它来创建一个列表,例如

你好啊 你好 ab 你好交流 ... 你好巴 你好bb 你好,公元前 等等……

另外...每个选项还有 2 个其他选项..

假设我想将后缀 1 添加为 a-z 并将后缀 2 添加为 0-9 然后就是

你好 a0 你好a1

有没有人可以帮助我?这就是我做单个字母递增的方式。

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

【问题讨论】:

  • 这听起来像XY Problem,你能解释更多你想要做什么吗?
  • this answer to a similar question可能对您有所帮助。 stackoverflow.com/questions/4583191/…
  • 我有一个术语(字符串)需要在末尾添加后缀。 a-z 或 0-9...或两者都按顺序... ... string + a-z 或 string + 0-9 或 string + 0-9 + a-z 或 string + a-z +0-9

标签: c#


【解决方案1】:

尝试使用这些扩展方法:

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;
}

然后这样称呼他们:

"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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2016-08-11
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2014-11-14
    相关资源
    最近更新 更多