我想构建一个列表,其中包含单词大写的所有可能排列。所以会是
List<string> permutate(string word)
{
List<string> ret = new List<string>();
MAGIC HAPPENS HERE
return ret;
}
所以说我输入 "happy"
我应该得到一个数组返回
{happy, Happy, hAppy, HAppy, haPpy, HaPpy ... haPPY, HaPPY, hAPPY, HAPPY}
我知道有很多函数可以将第一个字母大写,但我该如何处理单词中的任意字母?
最佳答案
如果将字符串转换为 char 数组,则可以修改单个字符。像这样的东西应该可以解决问题......
public static List<string> Permute( string s )
{
List<string> listPermutations = new List<string>();
char[] array = s.ToLower().ToCharArray();
int iterations = (1 << array.Length) - 1;
for( int i = 0; i <= iterations; i++ )
{
for( int j = 0; j < array.Length; j++ )
array[j] = (i & (1<<j)) != 0
? char.ToUpper( array[j] )
: char.ToLower( array[j] );
listPermutations.Add( new string( array ) );
}
return listPermutations;
}
关于c# - 大写排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/905317/