正在閱讀:字符串截取固定長(zhǎng)度的方法字符串截取固定長(zhǎng)度的方法

2004-03-23 14:45 出處:CSDN 作者:rexsp 責(zé)任編輯:linjixiong

  這個(gè)函數(shù)也沒有什么特別之處,就是可以截取一定長(zhǎng)度的字符串,可能小特點(diǎn)就是len是字節(jié),解決了漢字與英文字節(jié)不一樣導(dǎo)致直接截取到的長(zhǎng)度不一樣的問題,

  #region 字符串截取函數(shù)
  public static string CutString(string inputString,int len)
  {

   ASCIIEncoding ascii =  new ASCIIEncoding();
  int tempLen=0;
  string tempString="";
  byte[] s = ascii.GetBytes(inputString);
  for(int i=0;i<s.Length;i++)
  {
  if((int)s[i]==63)
  {
  tempLen+=2;
  }
  else
  {
  tempLen+=1;
  }
               
  try
  {
  tempString+=inputString.Substring(i,1);
  }
  catch
  {
  break;
  }

  if(tempLen>len)
  break;
  }
  //如果截過則加上半個(gè)省略號(hào)
  byte[] mybyte=System.Text.Encoding.Default.GetBytes(inputString);
  if(mybyte.Length>len)
  tempString+="…";

  return tempString;
  }
  #endregion


察看評(píng)論詳細(xì)內(nèi)容 我要發(fā)表評(píng)論
作者筆名簡(jiǎn)短內(nèi)容 發(fā)表時(shí)間
:
302 Found

302 Found


Powered by Tengine
tengine