<p>
</p>
<p>使用如下函数便好,其实inputString是源串,len是要截取的长度(以半角计算)。</p>
<p>原理很简单,就是逐个遍历源串中的字符,如果该字符是全角,则认为它占两个长度,如果是半角,就认为它占一个长度。</p>
<p> public static string CutString(string inputString, int len)</p>
<p> {</p>
<p> string tempString = string.Empty;</p>
<p> for (int i = 0, tempIndex = 0; i < inputString.Length; ++i, ++tempIndex)</p>
<p> {</p>
<p> if (System.Text.Encoding.UTF8.GetBytes(new char[] { inputString[i] }).Length > 1)</p>
<p> {</p>
<p> ++tempIndex;</p>
<p> }</p>
<p> if (tempIndex >= len)</p>
<p> {</p>
<p> tempString += "...";</p>
<p> break;</p>
<p> }</p>
<p> tempString += inputString[i];</p>
<p> }</p>
<p> return tempString;</p>
<p> }</p>
</p>
<p>使用如下函数便好,其实inputString是源串,len是要截取的长度(以半角计算)。</p>
<p>原理很简单,就是逐个遍历源串中的字符,如果该字符是全角,则认为它占两个长度,如果是半角,就认为它占一个长度。</p>
<p> public static string CutString(string inputString, int len)</p>
<p> {</p>
<p> string tempString = string.Empty;</p>
<p> for (int i = 0, tempIndex = 0; i < inputString.Length; ++i, ++tempIndex)</p>
<p> {</p>
<p> if (System.Text.Encoding.UTF8.GetBytes(new char[] { inputString[i] }).Length > 1)</p>
<p> {</p>
<p> ++tempIndex;</p>
<p> }</p>
<p> if (tempIndex >= len)</p>
<p> {</p>
<p> tempString += "...";</p>
<p> break;</p>
<p> }</p>
<p> tempString += inputString[i];</p>
<p> }</p>
<p> return tempString;</p>
<p> }</p>