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

如何通过循环实现带空格文本的单词组合所有可能性生成?

生成单词间空格保留/去除的所有组合(通用实现)

给定空格分隔的字符串,需要生成所有单词间空格可选保留或去除的组合。n个单词对应2^(n-1)种组合(每个间隙有2种选择),硬编码仅适用于少量单词,以下是通用循环实现的方案:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        string test = "aaa bbb ccc";
        foreach (var combination in GenerateAllCombinations(test))
        {
            Console.WriteLine(combination);
        }

        Console.WriteLine("\n--- 分割线 ---");

        string test2 = "aaa bbb ccc ddd";
        foreach (var combination in GenerateAllCombinations(test2))
        {
            Console.WriteLine(combination);
        }

        Console.ReadLine();
    }

    static IEnumerable<string> GenerateAllCombinations(string input)
    {
        // 分割字符串为单词数组,移除可能的空字符串(处理连续空格情况)
        string[] words = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
        int wordCount = words.Length;
        
        // 单词数少于2时,直接返回原字符串
        if (wordCount <= 1)
        {
            yield return input;
            yield break;
        }

        // 计算总组合数:2^(单词数-1),位运算比Math.Pow更高效
        int totalCombinations = 1 << (wordCount - 1);

        // 遍历所有组合
        for (int i = 0; i < totalCombinations; i++)
        {
            string result = words[0];
            // 遍历每个单词间隙(共wordCount-1个)
            for (int j = 0; j < wordCount - 1; j++)
            {
                // 用二进制位标记间隙选择:第j位为1则保留空格,否则去除
                if ((i & (1 << j)) != 0)
                {
                    result += " ";
                }
                result += words[j + 1];
            }
            yield return result;
        }
    }
}

代码关键说明

  • 鲁棒分割:通过StringSplitOptions.RemoveEmptyEntries处理输入中可能存在的连续空格,避免生成空单词。
  • 位运算优化:用1 << (wordCount-1)计算总组合数,比浮点数转换的Math.Pow效率更高。
  • 二进制映射逻辑:每个整数i的二进制位对应一个间隙的选择——第j位为1时,第j个间隙保留空格;为0时去除空格,完美覆盖所有组合场景。
  • 内存友好:使用yield return逐个返回组合,避免一次性生成大量字符串占用内存,适配单词数量较多的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:55:29