gpt4 book ai didi

c# - 在 C# 中选择具有重复字符的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:25 27 4
gpt4 key购买 nike

如何在 C# 中使用 linq 查询来查找同时包含“B”和“BZ”的字符串?要查找只有“B”的字符串,我使用:

var query = from c in mapping
where c.code.Contains("B")
select c;'

但是如果我说 where c.code.Contains("B") && where c.code.Contains("BZ")显然我只得到了有 BZ 的字符串,因为第一个约束将在第二个约束中得到满足。但我需要的是获得同时具有“B”和“BZ”的字符串。 (其实我的话应该有两个B)。

最佳答案

我建议使用正则表达式,例如:

    where Regex.Match(c, ".*(B.*BZ)|(BZ.*B).*").Success

示例:

    static void Main()
{
var mapping = new[]
{
"BBZ",
"B",
"ABBA",
"BZBZ",
"BZAB",
"BBZ",
"ZBBAZ"
};

// the code
var query = from c in mapping
where Regex.Match(c, ".*(B.*BZ)|(BZ.*B).*").Success
select c;

Console.WriteLine("Matched:");
foreach (string s in query)
{
Console.WriteLine(s);
}
}

输出:

Matched:
BBZ
BZBZ
BZAB
BBZ

关于c# - 在 C# 中选择具有重复字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28289073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com