asp.net中常用的字符串处理类

作者:袖梨 2022-06-25
代码如下 复制代码

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

namespace EC
{
///
/// 常用函数基类
///
public class FunObject
{
#region 替换字符串
///
/// 功能:替换字符
///
/// 字符串
/// 替换掉'的字符串
public static string FilterSQL(string strVAlue)
{
string str = "";
str = strVAlue.Replace("''", "");
return str;
}
#endregion

#region 对表 表单内容进行转换HTML操作,
///
/// 功能:对表 表单内容进行转换HTML操作,
///
/// html字符串
///
public static string HtmlCode(string fString)
{
string str = "";
str = fString.Replace(">", ">");
str = fString.Replace(" str = fString.Replace(" ", " ");
str = fString.Replace("n", "
");
str = fString.Replace("r", "
");
str = fString.Replace("rn", "
");

return str;
}
#endregion

#region 判断是否:返回值:√ or ×
///
/// 判断是否:返回值:√ or ×
///
/// true 或false
/// √ or ×
public static string Judgement(bool b)
{
string s = "";
if (b == true)
s = "√";
else
s = "×";
return s;
}
#endregion

#region 截取字符串
///
/// 功能:截取字符串长度
///
/// 要截取的字符串
/// 字符串长度
/// true:加...,flase:不加
///
public static string GetString(string str, int length, bool flg)
{
int i = 0, j = 0;
foreach (char chr in str)
{
if ((int)chr > 127)
{
i += 2;
}
else
{
i++;
}
if (i > length)
{
str = str.Substring(0, j);
if (flg)
str += "......";
break;
}
j++;
}
return str;
}
#endregion

#region 截取字符串+…
///
/// 截取字符串+…
///
///
///
///
public static string CutString(string strInput, int intlen)//截取字符串
{
ASCIIEncoding ascii = new ASCIIEncoding();
int intLength = 0;
string strString = "";
byte[] s = ascii.GetBytes(strInput);
for (int i = 0; i {
if ((int)s[i] == 63)
{
intLength += 2;
}
else
{
intLength += 1;
}

try
{
strString += strInput.Substring(i, 1);
}
catch
{
break;
}

if (intLength > intlen)
{
break;
}
}
//如果截过则加上半个省略号
byte[] mybyte = System.Text.Encoding.Default.GetBytes(strInput);
if (mybyte.Length > intlen)
{
strString += "…";
}
return strString;
}
#endregion

#region 字符串分函数
///
/// 字符串分函数
///
///
///
///
///
public string StringSplit(string strings, int index, string Separ)
{
string[] s = strings.Split(char.Parse(Separ));
return s[index];
}
#endregion

#region 分解字符串为数组
///
/// 字符串分函数
///
/// 要分解的字符串
/// 分割符,可以为string类型
/// 字符数组
public static string[] splitstr(string str, string splitstr)
{
if (splitstr != "")
{
System.Collections.ArrayList c = new System.Collections.ArrayList();
while (true)
{
int thissplitindex = str.IndexOf(splitstr);
if (thissplitindex >= 0)
{
c.Add(str.Substring(0, thissplitindex));
str = str.Substring(thissplitindex + splitstr.Length);
}
else
{
c.Add(str);
break;
}
}
string[] d = new string[c.Count];
for (int i = 0; i {
d[i] = c[i].ToString();
}
return d;
}
else
{
return new string[] { str };
}
}
#endregion

#region URL编码
///
/// URL编码
///
/// 字符串
///
public static string UrlEncoding(string str)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
return System.Text.Encoding.UTF8.GetString(bytes).ToString();
}
#endregion

#region 获取Web.config中的配置字段值
///
/// 获取全局配置参数
///
/// 键名
/// 参数
public static string GetApp(string key)
{
System.Configuration.AppSettingsReader appr = new System.Configuration.AppSettingsReader();
try
{
string str = (string)appr.GetValue(key, typeof(string));
if (str == null || str == "") return null;
return str;
}
catch (Exception E) { }
return null;
}

#endregion

#region 根据传入的字符串是否为yes/no返回Bit
///
/// 根据传入的字符串是否为yes/no返回Bit
///
///
///
public static int GetBitBool(string flg)
{
int str = 0;
switch (flg.ToLower())
{
case "yes":
str = 1;
break;
case"no":
str = 0;
break;
default:
break;
}
return str;
}
#endregion

#region Html编码
///
/// HTML编码
///
///
///
public static string HtmlEncode(string strInput)
{
string str;
try
{
str = HttpContext.Current.Server.HtmlEncode(strInput);
}
catch
{
str = "error";
}
return str;
}
///
/// HTML解码
///
///
///
public static string HtmlDecode(string strInput)
{
string str;
try
{
str = HttpContext.Current.Server.HtmlDecode(strInput);
}
catch
{
str = "error";
}
return str;
}
#endregion

#region 检测一个字符符,是否在另一个字符中,存在,存在返回true,否则返回false
///
/// 检测一个字符符,是否在另一个字符中,存在,存在返回true,否则返回false
///
/// 原始字符串
/// 目标字符串
///
public static bool IsEnglish(string srcString, string aimString)
{
bool Rev = true;
string chr;
if (aimString == "" || aimString == null) return false;
for (int i = 0; i {
chr = aimString.Substring(i, 1);
if (srcString.IndexOf(chr) {
return false;
break;
}

}
return Rev;
}
#endregion

#region 检测字符串中是否含有中文及中文长度
///
/// 检测字符串中是否含有中文及中文长度
///
/// 要检测的字符串
/// 中文字符串长度
public static int CnStringLength(string str)
{
ASCIIEncoding n = new ASCIIEncoding();
byte[] b = n.GetBytes(str);
int l = 0; // l 为字符串之实际长度
for (int i = 0; i {
if (b[i] == 63) //判断是否为汉字或全脚符号
{
l++;
}
}
return l;

}
#endregion

#region 取字符串右侧的几个字符
///
/// 取字符串右侧的几个字符
///
/// 字符串
/// 右侧的几个字符
///
public static string GetStrRight(string str, int length)
{
string Rev = "";

if (str.Length {
Rev = str;

}
else
{
Rev = str.Substring(str.Length - length, length);
}
return Rev;


}
#endregion

#region 替换右侧的字符串

///
/// 替换右侧的字符串
///
/// 字符串
/// 右侧的字符串
/// 要替换为的字符串
///
public static string RepStrRight(string str, string strsrc, string straim)
{

string Rev = "";
if (GetStrRight(str, strsrc.Length) != strsrc)
{
Rev = str;
}
else
{
Rev = str.Substring(0, str.Length - strsrc.Length).ToString() + straim.ToString();
}
return Rev;
}
#endregion
}

}

实例二

一些常用字符串操作的代码!大家直接看代码!!

代码如下 复制代码

using System;

namespace Web.StringUtil
{
///


/// 字符串操作工具集
///

public class StringUtil
{
public StringUtil()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

///


/// 从字符串中的尾部删除指定的字符串
///

///
///
///
public static string Remove(string sourceString,string removedString)
{
try
{
if( sourceString.IndexOf(removedString) {
throw new Exception("原字符串中不包含移除字符串!");
}
string result = sourceString;
int lengthOfSourceString = sourceString.Length;
int lengthOfRemovedString = removedString.Length;
int startIndex = lengthOfSourceString - lengthOfRemovedString;
string tempSubString = sourceString.Substring(startIndex);
if(tempSubString.ToUpper() == removedString.ToUpper())
{
result = sourceString.Remove(startIndex,lengthOfRemovedString);
}
return result;
}
catch
{
return sourceString;
}
}

///


/// 获取拆分符右边的字符串
///

///
///
///
public static string RightSplit(string sourceString, char splitChar)
{
string result=null;
string[] tempString = sourceString.Split(splitChar);
if(tempString.Length >0)
{
result = tempString[tempString.Length-1].ToString();
}
return result;
}

///
/// 获取拆分符左边的字符串
///

///
///
///
public static string LeftSplit(string sourceString, char splitChar)
{
string result=null;
string[] tempString = sourceString.Split(splitChar);
if(tempString.Length >0)
{
result = tempString[0].ToString();
}
return result;
}

///


/// 去掉最后一个逗号
///

///
///
public static string DelLastComma(string origin)
{
if(origin.IndexOf(",") == -1)
{
return origin;
}
return origin.Substring(0,origin.LastIndexOf(","));
}

///


/// 删除不可见字符
///

///
///
public static string DeleteUnVisibleChar(string sourceString)
{
System.Text.StringBuilder sBuilder = new System.Text.StringBuilder(131);
for(int i = 0;i {
int Unicode = sourceString[i];
if(Unicode >= 16)
{
sBuilder.Append(sourceString[i].ToString());
}
}
return sBuilder.ToString();
}

///


/// 获取数组元素的合并字符串
///

///
///
public static string GetArrayString(string[] stringArray)
{
string totalString = null;
for(int i=0;i {
totalString = totalString + stringArray[i];
}
return totalString;
}

///


/// 获取某一字符串在字符串数组中出现的次数
///

///
///
///
///

///
///
///
///
///

///
///
/// A int value
///

public static int GetStringCount(string[] stringArray,string findString)
{
int count = -1;
string totalString = GetArrayString(stringArray);
string subString = totalString;

while(subString.IndexOf(findString)>=0)
{
subString = totalString.Substring(subString.IndexOf(findString));
count += 1;
}
return count;
}

///


/// 获取某一字符串在字符串中出现的次数
///

///
///
/// 原字符串
///

///
///
///
/// 匹配字符串
///

///
///
/// 匹配字符串数量
///

public static int GetStringCount(string sourceString,string findString)
{
int count = 0;
int findStringLength = findString.Length;
string subString = sourceString;

while(subString.IndexOf(findString)>=0)
{
subString = subString.Substring(subString.IndexOf(findString)+findStringLength);
count += 1;
}
return count;
}

///


/// 截取从startString开始到原字符串结尾的所有字符
///

///
///
///
///

///
///
///
///
///

///
///
/// A string value
///

public static string GetSubString(string sourceString,string startString)
{
try
{
int index = sourceString.ToUpper().IndexOf(startString);
if(index>0)
{
return sourceString.Substring(index);
}
return sourceString;
}
catch
{
return "";
}
}

public static string GetSubString(string sourceString,string beginRemovedString,string endRemovedString)
{
try
{
if(sourceString.IndexOf(beginRemovedString)!=0)
{
beginRemovedString = "";
}

if(sourceString.LastIndexOf(endRemovedString,sourceString.Length - endRemovedString.Length) {
endRemovedString = "";
}
int startIndex = beginRemovedString.Length;
int length = sourceString.Length - beginRemovedString.Length - endRemovedString.Length ;
if(length>0)
{
return sourceString.Substring(startIndex,length);
}
return sourceString;
}
catch
{
return sourceString;;
}
}

///


/// 按字节数取出字符串的长度
///

/// 要计算的字符串
/// 字符串的字节数
public static int GetByteCount(string strTmp)
{
int intCharCount=0;
for(int i=0;i {
if(System.Text.UTF8Encoding.UTF8.GetByteCount(strTmp.Substring(i,1))==3)
{
intCharCount=intCharCount+2;
}
else
{
intCharCount=intCharCount+1;
}
}
return intCharCount;
}

///


/// 按字节数要在字符串的位置
///

/// 字符串的位置
/// 要计算的字符串
/// 字节的位置
public static int GetByteIndex(int intIns,string strTmp)
{
int intReIns=0;
if(strTmp.Trim()=="")
{
return intIns;
}
for(int i=0;i {
if(System.Text.UTF8Encoding.UTF8.GetByteCount(strTmp.Substring(i,1))==3)
{
intReIns=intReIns+2;
}
else
{
intReIns=intReIns+1;
}
if(intReIns>=intIns)
{
intReIns=i+1;
break;
}
}
return intReIns;
}
}
}

实例三

代码如下 复制代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace StringClass
{
public class StringHelper
{
///


/// 去掉字符串中的所有空格
///

///
///
public static string ReMoveBlank(string _str)
{
string strTemp = "";
CharEnumerator CEnumerator = _str.GetEnumerator();
while (CEnumerator.MoveNext())
{
byte[] array = new byte[1];
array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
int asciicode = (short)(array[0]);
if (asciicode != 32)
{
strTemp += CEnumerator.Current.ToString();
}
}
return strTemp;
}


///


/// 截取字符串并限制字符串长度,多于给定的长度+。。。
///

/// 待截取的字符串
/// 每行的长度,多于这个长度自动换行
/// 输出字符串最大的长度
///
public static string CutStr(string str, int len, int max)
{
string s = "";
string sheng = "";
if (str.Length > max)
{
str = str.Substring(0, max);
sheng = "";
}
for (int i = 0; i {
int r = i % len;
int last = (str.Length / len) * len;
if (i != 0 && i {
if (r == 0)
{
s += str.Substring(i - len, len) + "
";
}

}
else if (i > last)
{
s += str.Substring(i - 1);
break;
}

}
return s + sheng;
}

///


/// 截取字符串,不限制字符串长度
///

/// 待截取的字符串
/// 每行的长度,多于这个长度自动换行
///
public static string CutStr(string str, int len)
{
string s = "";
for (int i = 0; i {
int r = i % len;
int last = (str.Length / len) * len;
if (i != 0 && i {
if (r == 0)
{
s += str.Substring(i - len, len) + "
";
}
}
else if (i > last)
{
s += str.Substring(i - 1);
break;
}
}
return s;
}

public static string PartSubString(string str, int len)
{
if (str.Length > len)
{
return str.Substring(0, len) + "...";
}
return str;
}

///


///这个方法确保用户的输入不是恶毒的
///

/// 输入字符串
/// 最大长度
/// 转换后的字符串
public static string InputText(string text, int maxLength)
{
text = text.Trim();
if (string.IsNullOrEmpty(text))
return string.Empty;
if (text.Length > maxLength)
text = text.Substring(0, maxLength);
text = Regex.Replace(text, "[s]{2,}", " "); //two or more spaces
text = Regex.Replace(text, "()+|()", "n"); //

text = Regex.Replace(text, "(s*&[n|N][b|B][s|S][p|P];s*)+", " "); //
text = Regex.Replace(text, "", string.Empty); //any other tags
text = text.Replace("'", "''");
return text;
}

///


/// 字符串中大写字符转小写
///

///
///
public static string StringToLower(string str)
{
Char[] a = str.ToCharArray();
string strTemp = "";
for (int i = 0; i {
if (Convert.ToInt32(a[i]) >= 65 && Convert.ToInt32(a[i]) strTemp += a[i].ToString().ToLower();
else
strTemp += a[i].ToString();
}
return strTemp;
}

///


/// 加密
///

///
/// 必须是8位的字符串
///
public static string Encode(string str, int keyIndex)
{
ArrayList alKey = new ArrayList();
alKey.Add("BookT@#+!NumBq2");
alKey.Add("MagaZine@(21&*ID5");
alKey.Add("ThesisDSHI}._Y");
string key = alKey[keyIndex].ToString();
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
stream2.Write(bytes, 0, bytes.Length);
stream2.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte num in stream.ToArray())
{
builder.AppendFormat("{0:X2}", num);
}
stream.Close();
return builder.ToString();
}

///


/// Des 解密 GB2312
///

/// Desc string
/// Key ,必须为8位
///
public static string Decode(string str, int keyIndex)
{
ArrayList alKey = new ArrayList();
alKey.Add("BookT@#+!NumBq2");
alKey.Add("MagaZine@(21&*ID5");
alKey.Add("ThesisDSHI}._Y");
string key = alKey[keyIndex].ToString();
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i {
int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
buffer[i] = (byte)num2;
}
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
stream.Close();
return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());
}

///


/// MD5不可逆加密 32位
///

///
///
///
public static string GetMD5_32(string str1)
{
string cl1 = str1;
string pwd = "";
MD5 md5 = MD5.Create();
// 加密后是一个字节类型的数组
byte[] s = md5.ComputeHash(Encoding.Unicode.GetBytes(cl1));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 0; i {
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
pwd = pwd + s[i].ToString("x");
}
return pwd;
}
///
/// MD5不可逆加密 16位
///

///
///
public static string GetMd5_16(string ConvertString)
{

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);

t2 = t2.Replace("-", "");

return t2;

}
}
}

相关文章

精彩推荐