如何用前缀词排列 2 个字母?
像这样:
NAMEaa NAMEab NAMEac NAMEad NAMEae NAMEaf ... ...
for (char c1 = 'a'; c1 <= 'z'; c1++)
{
for (char c2 = 'a'; c2 <= 'z'; c2++)
{
Console.WriteLine("NAME" + c1 + c2);
}
}
顺便说一句,那些不是排列。
您可以使用 LINQ 轻松获得所需的结果:
string prefix = "NAME";
string alphabet = "abcdefghijklmnopqrstuvwxyz";
IEnumerable<string> words = from x in alphabet
from y in alphabet
select prefix + x + y;
创建一个包含所有字母的数组并循环遍历它的索引两次。
那不是排列,那是组合。
将您想要的字符放入字符串中:
string chars = "abcdefghijklmnopqrstuvwxyz";
可能的组合数量为:
int combinations = chars.Length * chars.Length;
要获得特定组合(0 到组合-1):
string str =
"NAME" +
chars.Substring(combination / chars.Length, 1) +
chars.Substring(combination % chars.Length, 1);
要获得所有组合,您只需遍历它们:
string chars = "abcdefghijklmnopqrstuvwxyz";
int combinations = chars.Length * chars.Length;
List<string> result = new List<string>();
for (int i = 0; i < combinations; i++) {
result.Add(
"NAME" +
chars.Substring(combination / chars.Length, 1) +
chars.Substring(combination % chars.Length, 1);
);
}