什么是可以处理代理对的 String.IndexOf(字符串输入)的 Unicode 安全副本?

What is a Unicode safe replica of String.IndexOf(string input) that can handle Surrogate Pairs?

我正在尝试找出与 C# string.IndexOf(string) 等效的方法,它可以处理 Unicode 字符中的代理项对。

我可以在只比较单个字符时获得索引,如下面的代码所示:

    public static int UnicodeIndexOf(this string input, string find)
    {
        return input.ToTextElements().ToList().IndexOf(find);
    }

    public static IEnumerable<string> ToTextElements(this string input)
    {
        var e = StringInfo.GetTextElementEnumerator(input);
        while (e.MoveNext())
        {
            yield return e.GetTextElement();
        }
    }

但是,如果我尝试实际使用字符串作为 find 变量,那么它将无法工作,因为每个文本元素只包含一个要比较的字符。

关于如何编写这篇文章,有什么建议吗?

感谢所有帮助。

编辑:

以下示例说明了为什么需要这样做:

代码

 Console.WriteLine("HolyCowBUBBYYYYY".IndexOf("BUBB"));
 Console.WriteLine("HolyCow@BUBBYY@YY@Y".IndexOf("BUBB"));

输出

9
8

请注意,我将 </code> 字符替换为 <code>@ 值发生了变化。

你基本上想在另一个字符串数组中找到一个字符串数组的索引。我们可以为此修改 this 问题中的代码:

public static class Extensions {
    public static int UnicodeIndexOf(this string input, string find, StringComparison comparison = StringComparison.CurrentCulture) {
        return IndexOf(
           // split input by code points
           input.ToTextElements().ToArray(),
           // split searched value by code points
           find.ToTextElements().ToArray(), 
           comparison);
    }
    // code from another answer
    private static int IndexOf(string[] haystack, string[] needle, StringComparison comparision) {
        var len = needle.Length;
        var limit = haystack.Length - len;
        for (var i = 0; i <= limit; i++) {
            var k = 0;
            for (; k < len; k++) {
                if (!String.Equals(needle[k], haystack[i + k], comparision)) break;
            }

            if (k == len) return i;
        }

        return -1;
    }

    public static IEnumerable<string> ToTextElements(this string input) {
        var e = StringInfo.GetTextElementEnumerator(input);
        while (e.MoveNext()) {
            yield return e.GetTextElement();
        }
    }
}