---
title: "中文字超长部分省略号显示"
author: "epai"
date: "2010-05-29T15:25:36Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2010-05-29T15:26:43Z"
id: 678791
url: "https://epai.iteye.com/blog/678791"
---

/// &lt;summary&gt;  
    /// 将指定字符串按指定长度进行剪切,超出部分以"..."代替  
    /// &lt;/summary&gt;  
    /// &lt;parm name = "oldStr"&gt;需要截断的字符串&lt;/parm&gt;  
    /// &lt;parm name = "maxLength"&gt;字符串的最大长度&lt;/parm&gt;  
    /// &lt;parm name = "endWith"&gt;超过长度的后缀&lt;/parm&gt;  
    /// &lt;return&gt;如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串&lt;/returns&gt;

    public static string StringTruncat(string oldStr, int maxLength, string endWith)  
    {  
        if (string.IsNullOrEmpty(oldStr))  
            // throw new NullReferenceException("原字符串不能为空");  
            return oldStr + endWith;  
        if (maxLength &lt; 1)  
            throw new Exception("返回的字符串长度必须大于\[0]");  
        if (oldStr.Length &gt; maxLength)  
        {  
            string strTmp = oldStr.Substring(0, maxLength);  
            if (string.IsNullOrEmpty(endWith))  
                return strTmp;  
            else  
                return strTmp + endWith;  
        }

        return oldStr;  
    }

 

前台部分

 &lt;%# StringTruncat(Eval("title").ToString(),8,"...") %&gt;

 

鼠标移至标题上时，标题内容显示完整

&lt;a href="showNews.aspx?id=&lt;%# Eval("id")%&gt;"   title="&lt;%# Eval("title") %&gt;"&gt;                                                  
                                                    &lt;%# StringTruncat(Eval("title").ToString(),8,"...") %&gt;  
                                                    &lt;/a&gt;