C#字符串的常用操作工具類代碼分享
實(shí)現(xiàn)以下功能:
驗(yàn)證字符串是否由正負(fù)號(hào)(+-)、數(shù)字、小數(shù)點(diǎn)構(gòu)成,并且最多只有一個(gè)小數(shù)點(diǎn)
驗(yàn)證字符串是否僅由[0-9]構(gòu)成
驗(yàn)證字符串是否由字母和數(shù)字構(gòu)成
驗(yàn)證是否為空字符串。若無(wú)需裁切兩端空格,建議直接使用 String.IsNullOrEmpty(string)
裁切字符串(中文按照兩個(gè)字符計(jì)算)
裁切字符串(中文按照兩個(gè)字符計(jì)算,裁切前會(huì)先過(guò)濾 Html 標(biāo)簽)
過(guò)濾HTML標(biāo)簽
獲取字符串長(zhǎng)度。與string.Length不同的是,該方法將中文作 2 個(gè)字符計(jì)算。
將形如 10.1MB 格式對(duì)用戶友好的文件大小字符串還原成真實(shí)的文件大小,單位為字節(jié)。
根據(jù)文件夾命名規(guī)則驗(yàn)證字符串是否符合文件夾格式
根據(jù)文件名命名規(guī)則驗(yàn)證字符串是否符合文件名格式
驗(yàn)證是否為合法的RGB顏色字符串
C#代碼:
public static class ExtendedString
{
/// <summary>
/// 驗(yàn)證字符串是否由正負(fù)號(hào)(+-)、數(shù)字、小數(shù)點(diǎn)構(gòu)成,并且最多只有一個(gè)小數(shù)點(diǎn)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumeric(this string str)
{
Regex regex = new Regex(@"^[+-]?\d+[.]?\d*$");
return regex.IsMatch(str);
}
/// <summary>
/// 驗(yàn)證字符串是否僅由[0-9]構(gòu)成
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumericOnly(this string str)
{
Regex regex = new Regex("[0-9]");
return regex.IsMatch(str);
}
/// <summary>
/// 驗(yàn)證字符串是否由字母和數(shù)字構(gòu)成
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumericOrLetters(this string str)
{
Regex regex = new Regex("[a-zA-Z0-9]");
return regex.IsMatch(str);
}
/// <summary>
/// 驗(yàn)證是否為空字符串。若無(wú)需裁切兩端空格,建議直接使用 String.IsNullOrEmpty(string)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
/// <remarks>
/// 不同于String.IsNullOrEmpty(string),此方法會(huì)增加一步Trim操作。如 IsNullOrEmptyStr(" ") 將返回 true。
/// </remarks>
public static bool IsNullOrEmptyStr(this string str)
{
if (string.IsNullOrEmpty(str)) { return true; }
if (str.Trim().Length == 0) { return true; }
return false;
}
/// <summary>
/// 裁切字符串(中文按照兩個(gè)字符計(jì)算)
/// </summary>
/// <param name="str">舊字符串</param>
/// <param name="len">新字符串長(zhǎng)度</param>
/// <param name="HtmlEnable">為 false 時(shí)過(guò)濾 Html 標(biāo)簽后再進(jìn)行裁切,反之則保留 Html 標(biāo)簽。</param>
/// <remarks>
/// <para>注意:<ol>
/// <li>若字符串被截?cái)鄤t會(huì)在末尾追加“...”,反之則直接返回原始字符串。</li>
/// <li>參數(shù) <paramref name="HtmlEnable"/> 為 false 時(shí)會(huì)先調(diào)用<see cref="uoLib.Common.Functions.HtmlFilter"/>過(guò)濾掉 Html 標(biāo)簽再進(jìn)行裁切。</li>
/// <li>中文按照兩個(gè)字符計(jì)算。若指定長(zhǎng)度位置恰好只獲取半個(gè)中文字符,則會(huì)將其補(bǔ)全,如下面的例子:<br/>
/// <code><![CDATA[
/// string str = "感謝使用uoLib。";
/// string A = CutStr(str,4); // A = "感謝..."
/// string B = CutStr(str,5); // B = "感謝使..."
/// ]]></code></li>
/// </ol>
/// </para>
/// </remarks>
public static string CutStr(this string str, int len, bool HtmlEnable)
{
if (str == null || str.Length == 0 || len <= 0) { return string.Empty; }
if (HtmlEnable == false) str = HtmlFilter(str);
int l = str.Length;
#region 計(jì)算長(zhǎng)度
int clen = 0;//當(dāng)前長(zhǎng)度
while (clen < len && clen < l)
{
//每遇到一個(gè)中文,則將目標(biāo)長(zhǎng)度減一。
if ((int)str[clen] > 128) { len--; }
clen++;
}
#endregion
if (clen < l)
{
return str.Substring(0, clen) + "...";
}
else
{
return str;
}
}
/// <summary>
/// 裁切字符串(中文按照兩個(gè)字符計(jì)算,裁切前會(huì)先過(guò)濾 Html 標(biāo)簽)
/// </summary>
/// <param name="str">舊字符串</param>
/// <param name="len">新字符串長(zhǎng)度</param>
/// <remarks>
/// <para>注意:<ol>
/// <li>若字符串被截?cái)鄤t會(huì)在末尾追加“...”,反之則直接返回原始字符串。</li>
/// <li>中文按照兩個(gè)字符計(jì)算。若指定長(zhǎng)度位置恰好只獲取半個(gè)中文字符,則會(huì)將其補(bǔ)全,如下面的例子:<br/>
/// <code><![CDATA[
/// string str = "感謝使用uoLib模塊。";
/// string A = CutStr(str,4); // A = "感謝..."
/// string B = CutStr(str,5); // B = "感謝使..."
/// ]]></code></li>
/// </ol>
/// </para>
/// </remarks>
public static string CutStr(this string str, int len)
{
if (IsNullOrEmptyStr(str)) { return string.Empty; }
else
{
return CutStr(str, len, false);
}
}
/// <summary>
/// 過(guò)濾HTML標(biāo)簽
/// </summary>
public static string HtmlFilter(this string str)
{
if (IsNullOrEmptyStr(str)) { return string.Empty; }
else
{
Regex re = new Regex(RegexPatterns.HtmlTag, RegexOptions.IgnoreCase);
return re.Replace(str, "");
}
}
/// <summary>
/// 獲取字符串長(zhǎng)度。與string.Length不同的是,該方法將中文作 2 個(gè)字符計(jì)算。
/// </summary>
/// <param name="str">目標(biāo)字符串</param>
/// <returns></returns>
public static int GetLength(this string str)
{
if (str == null || str.Length == 0) { return 0; }
int l = str.Length;
int realLen = l;
#region 計(jì)算長(zhǎng)度
int clen = 0;//當(dāng)前長(zhǎng)度
while (clen < l)
{
//每遇到一個(gè)中文,則將實(shí)際長(zhǎng)度加一。
if ((int)str[clen] > 128) { realLen++; }
clen++;
}
#endregion
return realLen;
}
/// <summary>
/// 將形如 10.1MB 格式對(duì)用戶友好的文件大小字符串還原成真實(shí)的文件大小,單位為字節(jié)。
/// </summary>
/// <param name="formatedSize">形如 10.1MB 格式的文件大小字符串</param>
/// <remarks>
/// 參見:<see cref="uoLib.Common.Functions.FormatFileSize(long)"/>
/// </remarks>
/// <returns></returns>
public static long GetFileSizeFromString(this string formatedSize)
{
if (IsNullOrEmptyStr(formatedSize)) throw new ArgumentNullException("formatedSize");
long size;
if (long.TryParse(formatedSize, out size)) return size;
//去掉數(shù)字分隔符
formatedSize = formatedSize.Replace(",", "");
Regex re = new Regex(@"^([\d\.]+)((?:TB|GB|MB|KB|Bytes))$");
if (re.IsMatch(formatedSize))
{
MatchCollection mc = re.Matches(formatedSize);
Match m = mc[0];
double s = double.Parse(m.Groups[1].Value);
switch (m.Groups[2].Value)
{
case "TB":
s *= 1099511627776;
break;
case "GB":
s *= 1073741824;
break;
case "MB":
s *= 1048576;
break;
case "KB":
s *= 1024;
break;
}
size = (long)s;
return size;
}
throw new ArgumentException("formatedSize");
}
/// <summary>
/// 根據(jù)文件夾命名規(guī)則驗(yàn)證字符串是否符合文件夾格式
/// </summary>
public static bool IsFolderName(this string folderName)
{
if (IsNullOrEmptyStr(folderName)) { return false; }
else
{
// 不能以 “.” 開頭
folderName = folderName.Trim().ToLower();
// “nul”、“aux”、“con”、“com1”、“l(fā)pt1”不能為文件夾/文件的名稱
// 作為文件夾,只需滿足名稱不為這幾個(gè)就行。
switch (folderName)
{
case "nul":
case "aux":
case "con":
case "com1":
case "lpt1":
return false;
default:
break;
}
Regex re = new Regex(RegexPatterns.FolderName, RegexOptions.IgnoreCase);
return re.IsMatch(folderName);
}
}
/// <summary>
/// 根據(jù)文件名命名規(guī)則驗(yàn)證字符串是否符合文件名格式
/// </summary>
public static bool IsFileName(this string fileName)
{
if (IsNullOrEmptyStr(fileName)) { return false; }
else
{
fileName = fileName.Trim().ToLower();
// 不能以 “.” 開頭
// 作為文件名,第一個(gè)“.” 之前不能是“nul”、“aux”、“con”、“com1”、“l(fā)pt1”
if (fileName.StartsWith(".")
|| fileName.StartsWith("nul.")
|| fileName.StartsWith("aux.")
|| fileName.StartsWith("con.")
|| fileName.StartsWith("com1.")
|| fileName.StartsWith("lpt1.")
) return false;
Regex re = new Regex(RegexPatterns.FileName, RegexOptions.IgnoreCase);
return re.IsMatch(fileName);
}
}
/// <summary>
/// 驗(yàn)證是否為合法的RGB顏色字符串
/// </summary>
/// <param name="color">RGB顏色,如:#00ccff | #039 | ffffcc</param>
/// <returns></returns>
public static bool IsRGBColor(this string color)
{
if (IsNullOrEmptyStr(color)) { return false; }
else
{
Regex re = new Regex(RegexPatterns.HtmlColor, RegexOptions.IgnoreCase);
return re.IsMatch(color);
}
}
public static string GetJsSafeStr(this string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
return str.Replace("\\", "\\\\").Replace("\"", "\\\"");
}
}
- C#通過(guò)屬性名字符串獲取、設(shè)置對(duì)象屬性值操作示例
- C#日期格式字符串的相互轉(zhuǎn)換操作實(shí)例分析
- Java字符串操作和C#字符串操作的不同小結(jié)
- C#減少垃圾回收壓力的字符串操作詳解
- C#操作字符串方法總結(jié)實(shí)例代碼
- 非常實(shí)用的C#字符串操作處理類StringHelper.cs
- C#實(shí)現(xiàn)字符串與圖片的Base64編碼轉(zhuǎn)換操作示例
- C# DataTable中Compute方法用法集錦(數(shù)值/字符串/運(yùn)算符/表等操作)
- 在C#及.NET框架中使用StringBuilder類操作字符串的技巧
- c#對(duì)字符串操作的技巧小結(jié)
- C#中一些字符串操作的常用用法
- c# 字符串操作總結(jié)
相關(guān)文章
C#中Property和Attribute的區(qū)別實(shí)例詳解
這篇文章主要介紹了C#中Property和Attribute的區(qū)別,較為詳細(xì)的分析了C#中Property和Attribute的功能、定義、區(qū)別及使用時(shí)的相關(guān)注意事項(xiàng),需要的朋友可以參考下2015-06-06Unity實(shí)現(xiàn)蘋果手機(jī)Taptic震動(dòng)
這篇文章主要介紹了Unity實(shí)現(xiàn)蘋果手機(jī)Taptic震動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10windows下C#定時(shí)管理器框架Task.MainForm詳解
這篇文章主要為大家詳細(xì)介紹了windows下C#定時(shí)管理器框架Task.MainForm的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06