首页 > 开发 > 综合 > 正文

对标题中特殊字符格式化,以便能换行显示

2024-07-21 02:29:30
字体:
来源:转载
供稿:网友

  最近做一个论坛,发现标题中如果有连续的字母或其他特殊字符,比如¥、$、。、,、~、!、、、?、*、…,这样将导致不能自动换行,解决的办法是使用如下方法,当标题中连续的字母或特殊字符达到一定的长度时,可以使用指定的tag来强制换行。

              public static string formatstr(string str, int len, string tag)

              {

                     char[] arrchar = new char[10]{ '。',',','~','!','、','?','*','…','¥','$'};

 

                     stringbuilder sb = new stringbuilder();

                     int i = 0;

                     foreach (char char in str)

                     {

                            bool biscontain = false;

                            for(int j = 0; j < arrchar.length; j++)

                            {

                                   if(char.compareto(arrchar[j]) == 0)

                                   {

                                          biscontain = true;

                                          break;

                                   }

                            }

 

                            if ((int)char <= 127 || biscontain)

                                   i += 1;

                            else

                                   i = 0;

 

                            sb.append(convert.tostring(char));

 

                            if(i > len)

                            {

                                   sb.append(tag);

                                   i = 0;

                            }

                     }

 

                     return sb.tostring();

              }

调用方法:
string str = "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$";
formatstr(str, 10, "<br>");

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表