Finding multiple indexes from source string

后端 未结 4 1561
眼角桃花
眼角桃花 2021-01-12 21:23

Basically I need to do String.IndexOf() and I need to get array of indexes from the source string.

Is there easy way to get array of indexes?

Before asking t

4条回答
  •  有刺的猬
    2021-01-12 21:50

    Using a solution that utilizes regex can be more reliable, using the indexOf function can be unreliable. It will find all matches and indexes, not matching an exact phrase which can lead to unexpected results. This function resolves that by making use of the Regex library.

    public static IEnumerable IndexesOf(string haystack, string needle)
    {
           Regex r = new Regex("\\b(" + needle + ")\\b");
           MatchCollection m = r.Matches(haystack);
    
           return from Match o in m select o.Index;
    }
    

提交回复
热议问题