就像标题一样。我得到了一个字符串数组和第二个字符串数组。我想以这种模式显示结果:第一个数组的第一个元素 - 然后是第二个数组中出现在第一个数组的第一个元素中的所有元素。之后,第一个数组的第二个元素以及第二个数组中出现在第一个数组的第二个元素中的所有元素。等等。 例如:
string[] arrayA = {"Lorem ipsum dolor sit amet, justo", "notgin like good cold beer"};
string[] arrayB = {"justo","beer","lorem"}
for (int i = 0; i < arrayA.Length; i++)
{
Console.WriteLine(arrayA[i]);
for (int j = 0; j < arrayB.Length; j++)
{
int controlIndex = arrayA[i].IndexOf(arrayB[j]);
if (controlIndex != -1)
{
Console.Write(" :--contains-->" + arrayB[j]);
}
}
}
所以结果应该是这样的:
- Lorem ipsum dolor sat amet,justo :--包含--> justo,lorem
- 不像优质冰镇啤酒:--包含--> 啤酒。
但我的结果是: - Lorem ipsum dolor sat amet, justo :--包含--> justo - 不像优质冰镇啤酒:--包含--> 啤酒。
如您所见,没有列出lorem
最佳答案
如果你把问题分解一些,这一点也不难。首先,不要处理数组和数组索引。只需使用 IEnumerable<T>
,它会让您的生活更轻松。
这是我的看法:
首先,您想要从数组 needles
中查找所有字符串,它们是字符串 haystack
的一部分.
public static IEnumerable<string> MatchingStrings(string haystack, IEnumerable<string> needles)
{
return needles.Where(needle => haystack.Contains(needle));
}
这将返回 needles
中所有字符串的 IEnumerable这是 haystack
的一部分.
然后,您想简单地迭代所有搜索字符串,我将其称为 haystacks
.
static void Main(string[] args)
{
var haystacks = new[] {
"Lorem ipsum dolor sit amet, justo",
"notgin like good cold beer"
};
var needles = new[] {"justo", "beer", "lorem"};
foreach (var haystack in haystacks) {
Console.Write(haystack + " contains --> ");
var matches = MatchingStrings(haystack, needles);
Console.WriteLine(String.Join(",", matches));
}
Console.ReadLine();
}
请注意String.Contains()
区分大小写。所以“Lorem”不会匹配“lorem”。如果您想要这种行为,则必须先将它们转换为小写。
public static IEnumerable<string> MatchingStringsCaseInsensitive(string haystack, IEnumerable<string> needles)
{
var h = haystack.ToLower();
return needles.Where(needle => h.Contains(needle.ToLower()));
}
关于C# - 使用另一个字符串数组中的字符串搜索字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596835/