C# 在字符串中添加“\r”换行符 实现lable自动换行

来源:互联网 发布:秦国为何灭亡 知乎 编辑:程序博客网 时间:2024/05/23 01:23

按字节截取字符串,并在规定位置添加换行符【\r】,解决lable自动换行问题


public static string CutString(string inputString)
        {
            ASCIIEncoding ascii = new ASCIIEncoding();
            int len = 30;
            int tempLen = 0;
            int j=0;
            string newstr = ""; ;
            string tempString = "";
            string[] str_temp = new string[10];
            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }


                try
                {
                    tempString += inputString.Substring(i, 1);
                }
                catch
                {
                    break;
                }


                if (tempLen > len)
                {
                    tempString = tempString + "\r";
                    str_temp[j] = tempString;
                    tempLen = 0;
                    tempString = "";
                    j++;
                }
                 
            }
            str_temp[j] = tempString;
            for (int l = 0; l <= j; l++)
            {
                newstr = newstr + str_temp[l];
            }


            return newstr;
        }