一个自动判断名字长度的函数

在游戏中会遇到名字过长的情况,做了一个小函数来对名字进行格式化。其中英文字符占1位,中文占2位。 

 

//nicName为你要格式化的名字。   length为你要保存的长度,为中文长度。

public static string GetName(string nicName,int length){
            char[] arr= nicName.ToCharArray ();
            int count=0;
            string temp="";
            StringBuilder outPut=new StringBuilder();
            for (int i = 0; i < arr.Length; i++) {
                if (count <= 2*(length-1)) {
                    if (!ischinese ((int)arr [i])){
                        count = count + 1;
                        outPut.Append (arr [i]);

                    } else {
                        count = count + 2;
                        outPut.Append (arr [i]);
                        Debug.Log (arr [i]);
                    }
                } else {
                    return temp+"...";
                }

                if (count == 2*length || count == 2*length-1) {
                    temp = outPut.ToString ();
                }
            }
            return outPut.ToString();
        }
    public static bool ischinese(int c){
        return c > 127;
    }

posted @ 2017-11-03 11:55  萌新小L  阅读(502)  评论(0编辑  收藏  举报