asp.net中字符串处理2

 public sealed class cleanstring
 {

  #region 数字字符串检查

  private static regex _isnumber = new regex("^[0-9]+$");
  
  /检查request查询字符串的键值,是否是数字,最大长度限制
  / return a digit string based on input data
  / look first in the querystring collection,
  /then in form return string.empty if not found or if non-digit
  public static string fetchinputdigit(httprequest req, string inputkey, int maxlen)
  {
   string retval = string.empty;
   if(inputkey != null && inputkey != string.empty)
   {
    retval = req.querystring[inputkey];
    if(null == retval)
     retval = req.form[inputkey];

    if(null != retval)
    {
     retval = cleanstring.sqltext(retval, maxlen);
     if(!isnumber(retval))
      retval = string.empty;
    }
   }

   if(retval == null)
    retval = string.empty;

   return retval;
  }


  /是否数字字符串
  public static bool isnumber(string inputdata)
  {
   match m = _isnumber.match(inputdata);
   return m.success;
  }
  /是否数字字符串
  public static bool isnumberint(string inputdata)
  {
   try
   {
    int.parse(inputdata);
   }
   catch
   {
    return false;
   }
   return true;
  }
  /是否数字字符串
  public static bool isnumberdecimal(string inputdata)
  {
   try
   {
    decimal.parse(inputdata);
   }
   catch
   {
    return false;
   }
   return true;
  }

  
  /字符串编码
  public static string htmlencode(string inputdata)
  {
   return httputility.htmlencode(inputdata);
  }


  public static void setlabel(label lbl, string txtinput)
  {
   lbl.text = htmlencode(txtinput);
  }

  public static void setlabel(label lbl, object inputobj)
  {
   setlabel(lbl, inputobj.tostring());
  }

  
  // <summary>
  // 检查字符串最大长度,返回指定长度的串
  // </summary>
  // <param name="sqlinput">输入字符串</param>
  // <param name="maxlength">最大长度</param>
  // <returns></returns>   
  public static string sqltext(string sqlinput, int maxlength)
  {   
   if(sqlinput != null && sqlinput != string.empty)
   {
    sqlinput = sqlinput.trim();
       
    if(sqlinput.length > maxlength)/按最大长度截取字符串
     sqlinput = sqlinput.substring(0, maxlength);
   }

   return sqlinput;
  }


  #endregion


  /字符串清理
  public static string inputtext(string inputstring, int maxlength)
  {   
   stringbuilder retval = new stringbuilder();

   / 检查是否为空
   if ((inputstring != null) && (inputstring != string.empty))
   {
    inputstring = inputstring.trim();

    
    /检查长度
    if (inputstring.length > maxlength)
     inputstring = inputstring.substring(0, maxlength);

    
    /替换危险字符
    for (int i = 0; i < inputstring.length; i++)
    {
     switch (inputstring[i])
     {
      case '"':
       retval.append("&quot;");
       break;
      case '<':
       retval.append("&lt;");
       break;
      case '>':
       retval.append("&gt;");
       break;
      default:
       retval.append(inputstring[i]);
       break;
     }
    }

    / 替换单引号
    retval.replace("'", " ");
   }

   return retval.tostring();
   
  }
 }

posted @ 2006-11-24 12:33  '.Elvis.'  阅读(171)  评论(0编辑  收藏  举报