如何扭转包含代理对的字符串 [英] How to reverse a string that contains surrogate pairs

查看:164
本文介绍了如何扭转包含代理对的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个方法来扭转一个字符串

I have written this method to reverse a string

public string Reverse(string s)
        {
            if(string.IsNullOrEmpty(s)) 
                return s;

            TextElementEnumerator enumerator =
               StringInfo.GetTextElementEnumerator(s);

            var elements = new List<char>();
            while (enumerator.MoveNext())
            {
                var cs = enumerator.GetTextElement().ToCharArray();
                if (cs.Length > 1)
                {
                    elements.AddRange(cs.Reverse());
                }
                else
                {
                    elements.AddRange(cs);
                }
            }

            elements.Reverse();
            return string.Concat(elements);
        }

现在,我并不想开始一个关于这个代码怎么会讨论更有效率或如何有单行,我可以用代替。我知道,您可以执行异或和各种其他的事情可能改善该代码。如果我要重构代码,后来因为我有单元测试我能做到这一点很容易。

Now, I don't want to start a discussion about how this code could be made more efficient or how there are one liners that I could use instead. I'm aware that you can perform Xors and all sorts of other things to potentially improve this code. If I want to refactor the code later I could do that easily as I have unit tests.

目前,这个正确反转BML字符串(包括口音的字符串如悲惨世界),并包含字符串组合字符,如莱斯Mise\\\́rables

Currently, this correctly reverses BML strings (including strings with accents like "Les Misérables") and strings that contain combined characters such as "Les Mise\u0301rables".

我的测试包含如果他们表达了这样的代理对工作

My test that contains surrogate pairs work if they are expressed like this

这篇关于如何扭转包含代理对的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆