资本的置换资本

2023-09-06 09:45:40 作者:上瘾

我想建立一个包含单词的大小写的每一种可能的排列名单。所以这将是

I want to build a list containing every possible permutation of capitalization of a word. so it would be

List<string> permutate(string word)
{
    List<string> ret = new List<string>();
    MAGIC HAPPENS HERE
    return ret;
}

所以说,我把开心我应该得到一个数组回来

So say I put in "happy" I should get an array back of

{开心,快乐,幸福,开心,快乐,幸福......幸福,快乐,幸福,快乐}

{happy, Happy, hAppy, HAppy, haPpy, HaPpy ... haPPY, HaPPY, hAPPY, HAPPY}

我知道很多的功能,将首字母大写,但我怎么做任意的字母词?

I know of plenty of functions that will capitalize the first letter but how do I do any arbitrary letter in the word?

推荐答案

如果您将您的字符串字符数组可以修改个别字符。像这样的东西应该做的伎俩......

You can modify individual characters if you convert your string to an array of char. Something like this should do the trick...

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;
}