猿问

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

我试图找出一个等效的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("HolyCow?BUBBYY?YY?Y".IndexOf("BUBB"));

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

输出


9

8

请注意,我在哪里?用@值更改替换了字符。


一只甜甜圈
浏览 127回答 1
1回答

蝴蝶刀刀

您基本上想在另一个字符串数组中找到一个字符串数组的索引。我们可以根据以下问题改编代码:public static class Extensions {&nbsp; &nbsp; public static int UnicodeIndexOf(this string input, string find, StringComparison comparison = StringComparison.CurrentCulture) {&nbsp; &nbsp; &nbsp; &nbsp; return IndexOf(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// split input by code points&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;input.ToTextElements().ToArray(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// split searched value by code points&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;find.ToTextElements().ToArray(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;comparison);&nbsp; &nbsp; }&nbsp; &nbsp; // code from another answer&nbsp; &nbsp; private static int IndexOf(string[] haystack, string[] needle, StringComparison comparision) {&nbsp; &nbsp; &nbsp; &nbsp; var len = needle.Length;&nbsp; &nbsp; &nbsp; &nbsp; var limit = haystack.Length - len;&nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i <= limit; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var k = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (; k < len; k++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!String.Equals(needle[k], haystack[i + k], comparision)) break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (k == len) return i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }&nbsp; &nbsp; public static IEnumerable<string> ToTextElements(this string input) {&nbsp; &nbsp; &nbsp; &nbsp; var e = StringInfo.GetTextElementEnumerator(input);&nbsp; &nbsp; &nbsp; &nbsp; while (e.MoveNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return e.GetTextElement();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答