c# - 如何使用字符串操作生成一整套组合?

标签 c# string combinations

我有一个小项目,我有一个输入句子,用户可以在其中指定变体:

The {small|big} car is {red|blue}

上面是一个例句,我想分成4个句子,像这样:

  • 小车是红色的
  • 大车是红色的
  • 小车是蓝色的
  • 大车是蓝色的

我似乎无法全神贯注地解决这个问题。也许有人可以帮助我。

编辑 这是我的初始代码

Regex regex = new Regex("{(.*?)}", RegexOptions.Singleline);
MatchCollection collection = regex.Matches(richTextBox1.Text);
string data = richTextBox1.Text;

//build amount of variations
foreach (Match match in collection)
{
    string[] alternatives = match.Value.Split(new char[] { '|', '{', '}' }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string alternative in alternatives)
    {
        //here i get problems                  
    }
}

最佳答案

听起来您需要为此使用动态笛卡尔函数。埃里克·利珀特的 blog post为回应 Generating all Possible Combinations 而写.

首先,我们需要解析输入的字符串:

Regex ex = new Regex(@"(?<=\{)(?<words>\w+(\|\w+)*)(?=\})");
var sentence = "The {small|big} car is {red|blue}";

然后应该修改输入字符串以用于类似string.Format的函数:

int matchCount = 0;
var pattern = ex.Replace(sentence, me => 
{
    return (matchCount++).ToString(); 
});
// pattern now contains "The {0} car is {1}"

然后我们需要找到所有匹配项并应用 Eric 出色的 CartesianProduct 扩展方法:

var set = ex.Matches(sentence)
    .Cast<Match>()
    .Select(m => 
        m.Groups["words"].Value
            .Split('|')
    ).CartesianProduct();

foreach (var item in set)
{
    Console.WriteLine(pattern, item.ToArray());
}

这将产生:

The small car is red
The small car is blue
The big car is red
The big car is blue

and, finally, the CartesianProduct method (taken from here):

static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
    this IEnumerable<IEnumerable<T>> sequences) 
{ 
  IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; 
  return sequences.Aggregate( 
    emptyProduct, 
    (accumulator, sequence) =>  
      from accseq in accumulator  
      from item in sequence  
      select accseq.Concat(new[] {item}));                
}

关于c# - 如何使用字符串操作生成一整套组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5392500/

相关文章:

c# - Linq 查询 ToList() 运行

c# - Azure - 从辅助角色访问与 Web 角色中相同的 blob

java - 从包含多行的字符串中获取最后一行

c# - INotifyPropertyChanged包装器

c# - 你如何获得被选中项目的索引号?

php - 从url获得一些值(value)?

java - 如何使用 UUID() 生成以字母开头的唯一 ID

c++ - 如何购买元素的组合

python - 总结在 R 或 Python 中赢得最后 N 场比赛中的 X 场的所有方法

java - java中与BigInteger的组合