gpt4 book ai didi

c# - 从源字符串中查找多个索引

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:38:20 26 4
gpt4 key购买 nike

基本上我需要执行 String.IndexOf() 并且我需要从源字符串中获取索引数组。

有没有简单的方法获取索引数组?

在问这个问题之前,我在谷歌上搜索了很多,但没有找到解决这个简单问题的简单方法。

最佳答案

这个扩展方法怎么样:

public static IEnumerable<int> IndexesOf(this string haystack, string needle)
{
int lastIndex = 0;
while (true)
{
int index = haystack.IndexOf(needle, lastIndex);
if (index == -1)
{
yield break;
}
yield return index;
lastIndex = index + needle.Length;
}
}

请注意,在“XAAAY”中查找“AA”时,此代码现在只会产生 1。

如果您确实需要一个数组,请对结果调用 ToArray()。 (这是假设 .NET 3.5,因此支持 LINQ。)

关于c# - 从源字符串中查找多个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/767767/

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