发新话题
打印

[编程代码] 截取固定长度字符串显示在页面

截取固定长度字符串显示在页面

以下是代码,呵呵,比较简单,主要是区分汉字和字母,不然一个全是字母,一个全是汉字的两条记录排列在一起时会比较难看,全字符的长度只有全汉字 的一半就显示...号了: |1 N4 Z3 {& B' i4 |; q" R
     public static string stringformat(string str,int n)4 [" o5 i$ C8 |: z: Y6 V# _4 j, g
         {6 p7 i8 H( \8 }& c8 Q; |5 a  \
                  
# }3 }6 }  x" `# T                          ///格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
$ `- \' A  S( v* q0 q) {; u" _                      ///
$ ^* P. b0 Q9 ^( o1 j8 Z                    string temp=string.Empty;
( p6 q7 m' r- |6 ~) a/ b/ K4 P       if(System.Text.Encoding.Default.GetByteCount(str)<=n)//如果长度比需要的长度n小,返回原字符串
+ f5 T3 d, n  h# _; }6 |                {
1 q6 d1 ?3 K% e1 {7 y                                  return str;
* y" s+ G& r1 k            }
) }* Y7 |0 k4 I1 D* U7 g+ d                     else
; F1 @8 s/ ^# E6 ^                          {
) a0 X! f! s2 R/ e4 }" O                             int t=0;, w% K9 y% g# h5 g0 m9 }
                                 char[] q=str.ToCharArray();" b* {, V5 u0 E! S. ~; r7 y+ f
                                  for(int i=0;i<q.Length&&t<n;n;i  )/ e- S7 [$ a2 u6 K! w! ^
                                  {
* e% v4 O! t' E. p                                     if((int)q>=0x4E00 && (int)q<=0x9FA5)//是否汉字
( L6 ?& H6 P* Q1 r6 f                                          {
* ~$ h# A) z: w. S4 m                                                  temp =q;
" O' S2 v. T  q: V# C                                                t =2;: S. Y" }9 f3 `4 ~4 e# _; d$ \
                                          }) k* o$ R/ ^0 s
                                     else- f7 I0 [% K# }8 A* ^& k) d1 P  U# v4 U
                                          {
; o* W& M6 ~+ \) {3 ]* {                                                temp =q;
* b6 c4 x( j* r' a! p( H                                          }
& d4 s/ i% \& r, e0 g* ~4 e% ~                                  }* j9 A0 Y& M# O6 A" A8 m* k
                                 return (temp "...");( o; p4 X3 L' X3 N% I+ t4 o
                          }
  r0 g: d6 B/ w6 C                  # @6 r- U8 Y& M: y# {- V# w7 d
              }

高效的固定长度字符串的截取函数

高效的固定长度字符串的截取函数--只要一次截取和一次正则替换就可以办到: & h$ d0 x2 w! |  I9 D; a
( b/ _; X: r0 T, g5 B
<? 8 c$ i6 t: E8 S+ t8 N$ {0 |4 [

# U% Q" p# ^* Z2 sfunction toFixLen($str,$len){ //固定长度字符串的截取8 H" H8 [/ q# c8 ]
    if($len>=strlen($str)||!$len) return $str; ( {: [" Z* B. J4 L
8 d: x' y, I! b, M) l8 G* s6 ^3 P
    $len-=3; - _+ d1 S- ^( g# {# l
    $tempstr1 = substr($str,0,$len); //截取字符串 4 r; a# Y5 p7 `* ^/ z
    $tempstr2 = preg_replace('/([x81-xff]+)$/ms','',$tempstr1,1); //去掉结尾的连续汉字字符 4 N& e9 M; c6 X0 h$ G
    if(!is_int((strlen($tempstr1)-strlen($tempstr2))/2)){ //去掉的字符为奇数? . Z/ r: r% u0 j" L0 k4 Q/ ^
        $tempstr1 = substr($str,0,$len-1); " I9 _( t6 A( L& y3 n
    }
! p$ {1 U5 W6 U$ h4 [1 w6 ?: F3 ~    return $tempstr1."..."; $ M+ r( y! w. c7 W4 r" J# C
} * e7 n) D" N# ~' Q+ v& ~4 V

/ c6 a( ?( ?9 M, M  i- z?>

TOP

发新话题