asp.net准确截取文本长度(取得标题的字符数)

来源:互联网 发布:易知投资 怎么样 编辑:程序博客网 时间:2024/05/17 21:42

asp.net中自带的CutString只能截取字符数量的长度,但中英文字符数有差异,一个中文字等同于二个英文字符的宽度,这样对截取后的效果不理想.使用以下的方法就能解决.

 

 

//调用方法
string title=BLL.CutStr.CutString("标题",10);

 

 

using System;
using System.Collections.Generic;
using System.Text;

namespace BLL
{
    
public  class CutStr
    {

        
public static string  CutString(string str, int length)
        {
            
if (str == "" )
            {
                str 
= "没有信息";
            }
            
else
            {
                
int i = 0, j = 0;
                
foreach (char chr in str)
                {
                    
if ((int)chr > 127)
                    {
                        i 
+= 2;
                    }
                    
else
                    {
                        i
++;
                    }
                    
if (i > length)
                    {
                        str 
= str.Substring(0, j) ;
                        
//str = str.Substring(0, j) + "...";
                        break;
                    }
                    j
++;
                }
               
            }
            
return str;
        }


   

    }
}

 

原创粉丝点击