使用增量顺序打印所有字符串组合而不重复

时间:2013-11-20 03:04:58

标签: c# string

我有一个字符串

这样做我正在做:

    string[] combinations = Combinations("LEQN");
    foreach (string s in combinations)
    {
        Console.WriteLine(s);
    }

和方法组合:

public static string[] Combinations(string str)
         {
            if (string.IsNullOrEmpty(str))  throw new ArgumentException("Invalid input");
            if (str.Length == 1)            return new string[] { str };
            // read the last character
            char c = str[str.Length - 1];
            // apart from the last character send remaining string for further processing
            string[] returnArray = Combinations(str.Substring(0, str.Length - 1));
            // List to keep final string combinations
            List<string> finalArray = new List<string>();
            // add whatever is coming from the previous routine
            foreach (string s in returnArray)
                finalArray.Add(s);
            // take the last character
            finalArray.Add(c.ToString());
            // take the combination between the last char and the returning strings from the previous routine
            foreach (string s in returnArray)
                finalArray.Add(s + c);

            return finalArray.ToArray();
        }

这会打印出来:

L
E
LE
Q
LQ
EQ
LEQ
N
LN
EN
LEN
QN
LQN
EQN
LEQN

这是正确的,但是我想得到像

这样的结果
L   N   Q   E   LN  NQ  EL  QE  LNQ ELN QEL NQE NQEL

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ length

对字符串OrderBy进行排序
foreach (string s in combinations.OrderBy(str => str.Length))
{
    Console.WriteLine(s);
}
相关问题