博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

String的一些常用函数

Posted on 2013-03-12 23:40  Hamilton Tan  阅读(295)  评论(0编辑  收藏  举报

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Globalization;
using System.IO;

namespace Net
{
/// <summary>
/// String的一些常用函数。
/// </summary>
public class StringUtil
{
public static readonly DateTime december31st1899 = new DateTime(1899, 12, 31);
public static readonly TimeSpan after1stMarchAdjustment = new TimeSpan(1, 0, 0, 0);
public static readonly DateTime march1st1900 = new DateTime(1900, 03, 01);

/// <summary>
/// check给定string是否为空或者0长度
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool isEmpty(string str)
{
return (str == null || str.Length == 0);
}

/// <summary>
/// 把给定的对象转换成整数
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static int parseInt(object o)
{
return (int)Math.Floor(parseDouble(o));
}

/// <summary>
/// 把给定的对象转换成浮点数
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static double parseDouble(object o)
{
if (o == null)
{
return 0;
}
else if (isEmpty(o.ToString()))
{
return 0;
}
else
{
return double.Parse(o.ToString());
}
}

/// <summary>
/// 把给定的对象转换成布尔型
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static bool parseBool(object o)
{
if (o == null)
{
return false;
}
else if (isEmpty(o.ToString()))
{
return false;
}
else
{
return bool.Parse(o.ToString());
}
}

/// <summary>
/// 把"0","1"类型的对象转换成布尔型:("0":转换成false,"1"转换成true)
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static bool parseIntStr(string o)
{
if (isEmpty(o) || "0".Equals(o))
{
return false;
}
else if ("1".Equals(o))
{
return true;
}
else
{
return bool.Parse(o);
}
}
/// <summary>
/// .转换html文本到纯文本
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string html2txt(string str)
{
str = str.Replace("&nbsp;", " ").Replace("&lt;", "<").Replace("&gt", ">").Replace("<br>", "\r\n");
return str;
}

public static string formatString(string str, string format)
{
if (isEmpty(str))
{
str = "";
}
else
{
double temp = 0;
temp = Convert.ToDouble(str);
str = String.Format(format, temp);
}
return str;
}

/// <summary>
/// 检验日期格式是否正确
/// </summary>
#region static bool string isDateFormat(string strDate)
public static bool isDateFormat(string strDate)
{
strDate = strDate.Trim();

Regex r1 = new Regex(@"^(?<year>[1-9][0-9]{0,3})/(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})$");
Regex r2 = new Regex(@"^(?<year>[1-9][0-9]{0,3})-(?<month>[0-9]{1,2})-(?<day>[0-9]{1,2})$");
Regex r3 = new Regex(@"^(?<year>[1-9][0-9]{0,3})年(?<month>[0-9]{1,2})月(?<day>[0-9]{1,2})日$");
Regex r4 = new Regex(@"^(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})/(?<year>[1-9][0-9]{0,3})$");


// 取得日期的年,月,日
string year, month, date;


if (Regex.IsMatch(strDate, @"^(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})/(?<year>[1-9][0-9]{3})$"))
{
year = r4.Match(strDate).Result("${year}");
month = r4.Match(strDate).Result("${month}");
date = r4.Match(strDate).Result("${day}");
}
else if (Regex.IsMatch(strDate, @"^(?<year>[1-9][0-9]{0,3})/(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})$"))
{
year = r1.Match(strDate).Result("${year}");
month = r1.Match(strDate).Result("${month}");
date = r1.Match(strDate).Result("${day}");
}
else if (Regex.IsMatch(strDate, @"^(?<year>[1-9][0-9]{0,3})-(?<month>[0-9]{1,2})-(?<day>[0-9]{1,2})$"))
{
year = r2.Match(strDate).Result("${year}");
month = r2.Match(strDate).Result("${month}");
date = r2.Match(strDate).Result("${day}");
}
else if (Regex.IsMatch(strDate, @"^(?<year>[1-9][0-9]{0,3})年(?<month>[0-9]{1,2})月(?<day>[0-9]{1,2})日$"))
{
year = r3.Match(strDate).Result("${year}");
month = r3.Match(strDate).Result("${month}");
date = r3.Match(strDate).Result("${day}");
}
else
{
return false;
}


// 最后检查日期的正确性
try
{
System.DateTime dt = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(date));
return true;
}
catch
{
return false;
}
}
#endregion

/// <summary>
/// .对日期型的日期进行计算
/// </summary>
/// <param name="inDate">传入的字符型基准日期</param>
/// <param name="format">传入的日期的格式,例如“YYYY/MM/DD”</param>
/// <param name="direction">是否计算将来的日期,true为计算将来日期,false为计算过去日期</param>
/// <param name="days">增减的天数</param>
/// <returns></returns>
public static string computeDate(string inDate, string format, bool direction, int days)
{
string strDate = inDate;
DateTime dt = Convert.ToDateTime(strDate);
if (direction)
{
dt = dt.AddDays(days);
}
else
{
dt = dt.AddDays(-days);
}

return dt.ToString(format);
}

/// <summary>
/// 将字符串中的单引号转换成DB中的表示方法
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string txt4sql(string str)
{
if (isEmpty(str))
{
return str;
}
else
{

return StripSQLInjection(str);
}
}

/// <summary>
/// 将字符串数组中的单引号转换成DB中的表示方法
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static object[] txt4sql(object[] arr)
{
if (arr == null)
{
return null;
}
else
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] is String)
{
arr[i] = txt4sql(arr[i].ToString());
}
}
return arr;
}
}
/// <summary>
/// 将字符串数组中的单引号转换成DB中的表示方法
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string[] txt4sql(string[] arr)
{
if (arr == null)
{
return null;
}
else
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] is String)
{
arr[i] = txt4sql(arr[i].ToString());
}
}
return arr;
}
}


public static int str2int(string str)
{
try
{
return int.Parse(str.Trim().Replace(",", ""));
}
catch
{
return 0;
}
}

//------------
public static string myReplace(string strSource, string strRe, string strTo)
{
string strSl, strRl;
strSl = strSource.ToLower();
strRl = strRe.ToLower();
int start = strSl.IndexOf(strRl);
if (start != -1)
{
strSource = strSource.Substring(0, start) + strTo
+ myReplace(strSource.Substring(start + strRe.Length), strRe, strTo);
}
return strSource;
}

public static bool IsPDF(string filename)
{
if (filename.Equals(string.Empty))
return false;

return Regex.IsMatch(filename, "\\.pdf$", RegexOptions.IgnoreCase);
}

/// <summary>
/// 将pdf等转换为swf文件
/// </summary>
/// <param name="appPath">转换程序路径</param>
/// <param name="Source">源文件</param>
/// <param name="Des">目标文件</param>
/// <returns></returns>
public static Boolean Doc2Swf(string appPath, string Source, string Des)
{
Process pc = new Process();
string strCmd = "\"" + Source + "\" -o \"" + Des + "\" -f -T 9";
ProcessStartInfo psi = new ProcessStartInfo(appPath, strCmd);
try
{
pc.StartInfo = psi;
pc.Start();
pc.WaitForExit();
}
catch
{
return false;
throw;
}
finally
{
pc.Close();
}
return File.Exists(Des);
}
//------------


/// <summary>
/// 判断是否是日期格式
/// </summary>
/// <param name="strDate"></param>
/// <returns></returns>
public static bool isDate(string strDate)
{
try
{
DateTime t1 = DateTime.Parse(strDate);
return true; //返回真
}
catch
{
return false;
}
}

/// </summary>
/// <param name="excelDate"></param>
/// <returns></returns>
public static string ConvertExcelDateToDate(string excelDate)
{
try
{

if ("".Equals(excelDate))
{
return "";
}
TimeSpan ts = TimeSpan.Parse(excelDate);
DateTime dt = december31st1899 + ts;
if (dt >= march1st1900)
{
return DateToStr(dt - after1stMarchAdjustment);
}

return DateToStr(dt);
}
catch
{
return "";
}
}

/// <summary>
/// 将字符型转成日期型(自定义日期格式)
/// </summary>
/// <param name="date">日期</param>
/// <param name="strFormat">自定义格式 eg. yyyy/MM/dd</param>
/// <returns></returns>
public static string DateToStr(DateTime date, string strFormat)
{
DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
dtfi.ShortDatePattern = strFormat;
return date.ToString("d", dtfi);
}

/// <summary>
/// 将字符型转成日期型(默认格式 yyyy/MM/dd)
/// </summary>
/// <param name="date">日期</param>
/// <returns></returns>
public static string DateToStr(DateTime date)
{
return DateToStr(date, "yyyy-MM-dd");
}
// 把字符串数组拼成用逗号隔开的字符串
public static string generateDotSpliteStr(string[] ls)
{
StringBuilder ret = new StringBuilder();;
if (ls == null || ls.Length == 0)
{
return "";
}

for (int i = 0; i < ls.Length; i++)
{
ret.Append("'");
ret.Append(ls[i]);
ret.Append("',");
}

ret.Remove(ret.Length - 1, 1);
return ret.ToString();
}

#region String length formatter
/// <summary>
/// 对字符串进行裁剪
/// </summary>
public static string Trim(string stringTrim, int maxLength)
{
return Trim(stringTrim, maxLength, "...");
}

/// <summary>
/// 对字符串进行裁剪(区分单字节及双字节字符)
/// </summary>
/// <param name="rawString">需要裁剪的字符串</param>
/// <param name="maxLength">裁剪的长度,按双字节计数</param>
/// <param name="appendString">如果进行了裁剪需要附加的字符</param>
public static string Trim(string rawString, int maxLength, string appendString)
{
if (string.IsNullOrEmpty(rawString) || rawString.Length <= maxLength)
{
return rawString;
}
else
{
int rawStringLength = Encoding.UTF8.GetBytes(rawString).Length;
if (rawStringLength <= maxLength * 2)
return rawString;
}

int appendStringLength = Encoding.UTF8.GetBytes(appendString).Length;
StringBuilder checkedStringBuilder = new StringBuilder();
int appendedLenth = 0;
for (int i = 0; i < rawString.Length; i++)
{
char _char = rawString[i];
checkedStringBuilder.Append(_char);

appendedLenth += Encoding.Default.GetBytes(new char[] { _char }).Length;

if (appendedLenth >= maxLength * 2 - appendStringLength)
break;
}

return checkedStringBuilder.ToString() + appendString;
}


#endregion
#region 特殊字符

/// <summary>
/// 检测是否有Sql危险字符
/// </summary>
/// <param name="str">要判断字符串</param>
/// <returns>判断结果</returns>
public static bool IsSafeSqlString(string str)
{
return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
}

/// <summary>
/// 删除SQL注入特殊字符
/// </summary>
public static string StripSQLInjection(string sql)
{
if (!string.IsNullOrEmpty(sql))
{
//替换 ' --''
string pattern1 = @"(\%27)|(\')|(\-\-)";

//防止执行 -- 和 or
string pattern2 = @"((\%27)|(\-\-))\s*((\%6F)|o|(\%4F))((\%72)|r|(\%52))";

//防止执行sql server 内部存储过程或扩展存储过程
string pattern3 = @"\s+exec(\s|\+)+(s|x)p\w+";

sql = Regex.Replace(sql, pattern1, "''", RegexOptions.IgnoreCase);
sql = Regex.Replace(sql, pattern2, string.Empty, RegexOptions.IgnoreCase);
sql = Regex.Replace(sql, pattern3, string.Empty, RegexOptions.IgnoreCase);
}
return sql;
}

public static string SQLSafe(string Parameter)
{
Parameter = Parameter.ToLower();
Parameter = Parameter.Replace("'", "''");
Parameter = Parameter.Replace(">", ">");
Parameter = Parameter.Replace("<", "<");
Parameter = Parameter.Replace("\n", "<br>");
Parameter = Parameter.Replace("\0", "·");
return Parameter;
}

/// <summary>
/// 清除xml中的不合法字符
/// </summary>
/// <remarks>
/// 无效字符:
/// 0x00 - 0x08
/// 0x0b - 0x0c
/// 0x0e - 0x1f
/// </remarks>
public static string CleanInvalidCharsForXML(string input)
{
if (string.IsNullOrEmpty(input))
return input;
else
{
StringBuilder checkedStringBuilder = new StringBuilder();
Char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
int charValue = Convert.ToInt32(chars[i]);

if ((charValue >= 0x00 && charValue <= 0x08) || (charValue >= 0x0b && charValue <= 0x0c) || (charValue >= 0x0e && charValue <= 0x1f))
continue;
else
checkedStringBuilder.Append(chars[i]);
}

return checkedStringBuilder.ToString();

//string result = checkedStringBuilder.ToString();
//result = result.Replace("&#x0;", "");
//return Regex.Replace(result, @"[\?-\\ \ \-\\?-\?]", delegate(Match m) { int code = (int)m.Value.ToCharArray()[0]; return (code > 9 ? "&#" + code.ToString() : "&#0" + code.ToString()) + ";"; });
}
}


/// <summary>
/// 改正sql语句中的转义字符
/// </summary>
public static string mashSQL(string str)
{
return (str == null) ? "" : str.Replace("\'", "'");
}

/// <summary>
/// 替换sql语句中的有问题符号
/// </summary>
public static string ChkSQL(string str)
{
return (str == null) ? "" : str.Replace("'", "''");
}

/// <summary>
/// 判断是否有非法字符
/// </summary>
/// <param name="strString"></param>
/// <returns>返回TRUE表示有非法字符,返回FALSE表示没有非法字符。</returns>
public static bool CheckBadStr(string strString)
{
bool outValue = false;
if (strString != null && strString.Length > 0)
{
string[] bidStrlist = new string[9];
bidStrlist[0] = "'";
bidStrlist[1] = ";";
bidStrlist[2] = ":";
bidStrlist[3] = "%";
bidStrlist[4] = "@";
bidStrlist[5] = "&";
bidStrlist[6] = "#";
bidStrlist[7] = "\"";
bidStrlist[8] = "net user";
bidStrlist[9] = "exec";
bidStrlist[10] = "net localgroup";
bidStrlist[11] = "select";
bidStrlist[12] = "asc";
bidStrlist[13] = "char";
bidStrlist[14] = "mid";
bidStrlist[15] = "insert";
bidStrlist[19] = "order";
bidStrlist[20] = "exec";
bidStrlist[21] = "delete";
bidStrlist[22] = "drop";
bidStrlist[23] = "truncate";
bidStrlist[24] = "xp_cmdshell";
bidStrlist[25] = "<";
bidStrlist[26] = ">";
string tempStr = strString.ToLower();
for (int i = 0; i < bidStrlist.Length; i++)
{
if (tempStr.IndexOf(bidStrlist[i]) != -1)
//if (tempStr == bidStrlist[i])
{
outValue = true;
break;
}
}
}
return outValue;
}

#endregion

#region Tools
/// <summary>
/// 去掉最后一个逗号
/// </summary>
/// <param name="String">要做处理的字符串</param>
/// <returns>去掉最后一个逗号的字符串</returns>
public static string DelLastComma(string String)
{
if (String.IndexOf(",") == -1)
{
return String;
}
return String.Substring(0, String.LastIndexOf(","));
}

/// <summary>
/// 删除最后一个字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ClearLastChar(string str)
{
return (str == "") ? "" : str.Substring(0, str.Length - 1);
}
/// <summary>
/// html编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
public static string html_text(string chr)
{
if (chr == null)
return "";
chr = chr.Replace("'", "''");
chr = chr.Replace("<", "<");
chr = chr.Replace(">", ">");
return (chr);
}
/// <summary>
/// html解码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
public static string text_html(string chr)
{
if (chr == null)
return "";
chr = chr.Replace("<", "<");
chr = chr.Replace(">", ">");
return (chr);
}
public static bool JustifyStr(string strValue)
{
bool flag = false;
char[] str = "^<>'=&*, ".ToCharArray(0, 8);
for (int i = 0; i < 8; i++)
{
if (strValue.IndexOf(str[i]) != -1)
{
flag = true;
break;
}
}
return flag;
}
public static string CheckOutputString(string key)
{
string OutputString = string.Empty;
OutputString = key.Replace("<br>", "\n").Replace("<", "<").Replace(">", ">").Replace(" ", " ");
return OutputString;

}
#endregion
}


}