我们在做项目时会需要对字符串进行特殊处理,以下提供C#(asp.net)对字符串的操作公共类,直接复制以下代码到新建cs文件StringUtil.cs中即可。
/// <summary>
/// StringUtil 的摘要说明。
/// </summary>
public class StringUtil
{
public StringUtil()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 功能描述:将字符串转换成参数。
/// </summary>
/// <param name="str">需转换的字符串</param>
/// <returns></returns>
public static string paramChg(string str)
{
str = "@"+str;
return str;
}
/// <summary>
/// 功能描述:从字符串中的尾部删除指定的字符串。
/// </summary>
/// <param name="sourceString">原字符串</param>
/// <param name="removedString">移除字符串</param>
/// <returns>留下的字符串</returns>
public static string Remove(string sourceString,string removedString)
{
try
{
if(sourceString.IndexOf(removedString)==-1)
throw new Exception("原字符串中不包含移除字符串!");
string result=sourceString;
int LengthOfsourceString=sourceString.Length;
int LengthOfremovedString=removedString.Length;
int startIndex=LengthOfsourceString-LengthOfremovedString;
string sourceStringSub=sourceString.Substring(startIndex);
if(sourceStringSub.ToUpper()==removedString.ToUpper())
{
result=sourceString.Remove(startIndex,LengthOfremovedString);
}
return result;
}
catch
{
return sourceString;
}
}
/// <summary>
/// 功能描述:从字符串中的指定位置删除指定的字符串。
/// </summary>
/// <param name="sourceString">原字符串</param>
/// <param name="removedString">移除字符串</param>
/// <returns>留下的字符串</returns>
public static string StrRemove(string sourceString,string removedString)
{
try
{
if(sourceString.IndexOf(removedString)==-1)
throw new Exception("原字符串中不包含移除字符串!");
string result=sourceString;
int LengthOfremovedString=removedString.Length;
if(sourceString.IndexOf(removedString)> 0)
{
int startIndex=sourceString.IndexOf(removedString);
result=sourceString.Remove(startIndex,LengthOfremovedString);
}
return result;
}
catch
{
return sourceString;
}
}
/// <summary>
/// 功能描述:获取拆分符右边的字符串。
/// </summary>
/// <param name="sourceString">原字符串</param>
/// <param name="splitChar">拆分字符</param>
/// <returns>右边的字符串</returns>