c# - 大写排列

标签 c# .net string capitalization

我想构建一个列表,其中包含单词大写的所有可能排列。所以会是

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/

相关文章:

c# - 了解异步 - 我可以等待同步方法吗?

c# - 如何检测程序是否在运行时抛出的异常下执行?

c# - 使用 HttpClient 和 Web API 方法 [FromBody] 参数发布到 Web API 最终为空

c# - 从 Uri.Segment.Last() 中删除结束斜线?

c# - 检查是否已在 SqlDataReader 上调用 read()

c - 优化字符串散列时出现奇怪的程序集输出

c++ - 检查字符串中的字符

C++ 从用户输入中将char转换为int

c# - EF7 一对多映射

c# - nVelocity 中 if false 的语法是什么?