【问题标题】:c# how to generate all combinations of a word by using char arrays for each position in a wordc#如何通过对单词中的每个位置使用char数组来生成单词的所有组合
【发布时间】:2019-02-13 12:39:32
【问题描述】:

嗨,我想生成一个单词的字典,然后基于表示可能构成该单词位置的可能字符的数组。我需要所有可能的大写和小写字母组合并替换某些带有符号 0、@ 和 5 的字母
我的意思是:

说这个词是“支持” 我需要生成一个包含所有可能组合的字典,例如: 5uPport、SupP0rt 或 SUPP0RT ...

我考虑过使用多个数组来表示每个字母,例如:

char[] s = {s,S,5};
char[] u = {U,u};

然后我有字符串来表示在创建单词的loops 之后我将加入的单词 support 中的位置,但是我不知道这会是什么样子。有没有更好的方法来做到这一点,请有人给我一个代码示例。

【问题讨论】:

  • 问题:为什么需要这本词典?当然我可以给你写几行代码来填充这个字典,但我猜你以后想用这个字典来匹配文本——在这种情况下,正则表达式可能是一个更好的解决方案。

标签: c# arrays string dictionary console


【解决方案1】:

以下应该可以解决问题:

public static IEnumerable<string> GetCombinations(
    string s,
    Dictionary<char, IEnumerable<char>> substitutions)
{
    IEnumerable<string> GetCombinations(
        string original, 
        string current, 
        int index)
    {
        if (index == original.Length)
        {
            yield return current;
        }
        else
        {
            if (substitutions.TryGetValue(
                original[index],
                out var chars))
            {
                foreach (var c in chars)
                {
                    foreach (var combination in
                        GetCombinations(original,
                                        current + c,
                                        index + 1))
                    {
                        yield return combination;
                    }
                }
            }
        }
    }

    if (string.IsNullOrEmpty(s))
        return Enumerable.Repeat(s, 1);

    var lowerCased = s.ToLower();
    return GetCombinations(lowerCased,
                           string.Empty,
                           0);
}

而你之前会称它为构建你的替换字典:

var substitutions = new Dictionary<char, IEnumerable<char>>();
substitutions.Add('s', new[] { 's', 'S', '5' });
substitutions.Add('o', new[] { 'o', 'O', '0' });
substitutions.Add('p', new[] { 'p','P' });
substitutions.Add('u', new[] { 'u', 'U' });
substitutions.Add('r', new[] { 'r', 'R' });
substitutions.Add('t', new[] { 't', 'T' });
Console.WriteLine(string.Join(
    Environment.NewLine,
    GetCombinations("support", substitutions)));

【讨论】:

  • 谢谢!我要测试一下!
  • @IT请您阅读两个主题,您会在 SO 中找到大量信息,或者只是在谷歌上搜索:递归和迭代器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 2022-08-24
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多