生成具有给定字符集和长度的所有字符串

本文关键字:字符串 字符集 | 更新日期: 2023-09-27 17:59:04

我想在C#.Net中生成具有给定集合和长度的所有可能的字符串。例如,设置为{+,-,0,1,2,3,4,5,6,7,8,9}(不总是数字)并且长度为4:

+001 ,
001+ ,
0+01 ,
12+1 ,
02-9 ,
1502 ,
...

生成具有给定字符集和长度的所有字符串

char[] chars = "+-0123456789".ToCharArray();
var strings =
    from a in chars
    from b in chars
    from c in chars
    from d in chars
    select new string(new[] { a, b, c, d });

它无效,但工作良好

   List<char> input;
    public static void Main()
    {
    input=new List<char>(){'+','-','0','1','2','3','4','5','6','7','8','9'};
            List<char> permutation = new List<char>();
            permutation.Add(input[0]);
            permutation.Add(input[0]);
            permutation.Add(input[0]);
                GetPermutation(ref permutation, input.Count); 
}
 private static void GetPermutation(ref List<char> permutation,int length)
        {

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    for (int k = 0; k < length; k++)
                    {
                        string output = "";
                        permutation[0] = input[k];
                        permutation[1] = input[j];
                        permutation[2] = input[i];
                        output += permutation[0];
                        output += permutation[1];
                        output += permutation[2];
                        Console.WriteLine(output + "'n");
                        count++;
                    }
                }
            }
        }