You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

路径字符串各段大小写排列组合生成及代码实现咨询

生成路径各段大小写组合的所有可能路径

你想要生成路径中每个目录/文件名段的大小写全组合的思路是对的,但当前代码有个关键问题——直接修改了原始的分割数组,这会导致后续迭代的结果被之前的修改污染,最终生成的组合会出现重复或者不符合预期的情况。

先看你写的原始代码:

var s = "dir1/dir2/Demo.txt";
List<string> listPermutations = new List<string>();
string[] array = s.Split('/');
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 ? array[j].ToUpper() : array[j];
    listPermutations.Add(string.Join("/",array ));
}

问题分析

比如第一次循环i=0时,所有段保持原大小写;但当i=1时,你把array[0]改成了大写,到i=2时,array[0]已经是大写状态了,此时判断(i & (1<<j)) !=0时,会基于已经修改过的数组处理,导致后续的组合不再是基于原始路径的全排列。

修正后的代码

解决方法很简单:每次迭代都基于原始数组的副本进行修改,避免污染原始数据。修改后的代码如下:

var s = "dir1/dir2/Demo.txt";
List<string> listPermutations = new List<string>();
string[] originalSegments = s.Split('/');
int totalCombinations = 1 << originalSegments.Length; // 等价于2^n,n是段数

for (int i = 0; i < totalCombinations; i++)
{
    // 每次循环都创建原始数组的副本
    string[] currentSegments = (string[])originalSegments.Clone();
    for (int j = 0; j < originalSegments.Length; j++)
    {
        // 判断当前位是否需要转大写
        if ((i & (1 << j)) != 0)
        {
            currentSegments[j] = currentSegments[j].ToUpper();
        }
        // 不需要转大写的话保持原始值,不用额外赋值
    }
    listPermutations.Add(string.Join("/", currentSegments));
}

输出效果

运行修正后的代码,就能得到你想要的所有大小写组合:

  • "dir1/dir2/Demo.txt"
  • "DIR1/dir2/Demo.txt"
  • "dir1/DIR2/Demo.txt"
  • "DIR1/DIR2/Demo.txt"
  • "dir1/dir2/DEMO.txt"
  • "DIR1/dir2/DEMO.txt"
  • "dir1/DIR2/DEMO.txt"
  • "DIR1/DIR2/DEMO.txt"

这样就能正确生成每个段的大小写全排列组合啦~

内容的提问来源于stack exchange,提问作者Lingraj Gowda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:47:41