手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#字符串的常用操作工具类代码分享
C#字符串的常用操作工具类代码分享
摘要:实现以下功能:验证字符串是否由正负号(+-)、数字、小数点构成,并且最多只有一个小数点验证字符串是否仅由[0-9]构成验证字符串是否由字母和...

实现以下功能:

验证字符串是否由正负号(+-)、数字、小数点构成,并且最多只有一个小数点

验证字符串是否仅由[0-9]构成

验证字符串是否由字母和数字构成

验证是否为空字符串。若无需裁切两端空格,建议直接使用 String.IsNullOrEmpty(string)

裁切字符串(中文按照两个字符计算)

裁切字符串(中文按照两个字符计算,裁切前会先过滤 Html 标签)

过滤HTML标签

获取字符串长度。与string.Length不同的是,该方法将中文作 2 个字符计算。

将形如 10.1MB 格式对用户友好的文件大小字符串还原成真实的文件大小,单位为字节。

根据文件夹命名规则验证字符串是否符合文件夹格式

根据文件名命名规则验证字符串是否符合文件名格式

验证是否为合法的RGB颜色字符串

C#代码:

复制代码 代码如下:

public static class ExtendedString

{

/// <summary>

/// 验证字符串是否由正负号(+-)、数字、小数点构成,并且最多只有一个小数点

/// </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>

/// 验证字符串是否仅由[0-9]构成

/// </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>

/// 验证字符串是否由字母和数字构成

/// </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>

/// 验证是否为空字符串。若无需裁切两端空格,建议直接使用 String.IsNullOrEmpty(string)

/// </summary>

/// <param name="str"></param>

/// <returns></returns>

/// <remarks>

/// 不同于String.IsNullOrEmpty(string),此方法会增加一步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>

/// 裁切字符串(中文按照两个字符计算)

/// </summary>

/// <param name="str">旧字符串</param>

/// <param name="len">新字符串长度</param>

/// <param name="HtmlEnable">为 false 时过滤 Html 标签后再进行裁切,反之则保留 Html 标签。</param>

/// <remarks>

/// <para>注意:<ol>

/// <li>若字符串被截断则会在末尾追加“...”,反之则直接返回原始字符串。</li>

/// <li>参数 <paramref name="HtmlEnable"/> 为 false 时会先调用<see cref="uoLib.Common.Functions.HtmlFilter"/>过滤掉 Html 标签再进行裁切。</li>

/// <li>中文按照两个字符计算。若指定长度位置恰好只获取半个中文字符,则会将其补全,如下面的例子:<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 计算长度

int clen = 0;//当前长度

while (clen < len && clen < l)

{

//每遇到一个中文,则将目标长度减一。

if ((int)str[clen] > 128) { len--; }

clen++;

}

#endregion

if (clen < l)

{

return str.Substring(0, clen) + "...";

}

else

{

return str;

}

}

/// <summary>

/// 裁切字符串(中文按照两个字符计算,裁切前会先过滤 Html 标签)

/// </summary>

/// <param name="str">旧字符串</param>

/// <param name="len">新字符串长度</param>

/// <remarks>

/// <para>注意:<ol>

/// <li>若字符串被截断则会在末尾追加“...”,反之则直接返回原始字符串。</li>

/// <li>中文按照两个字符计算。若指定长度位置恰好只获取半个中文字符,则会将其补全,如下面的例子:<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>

/// 过滤HTML标签

/// </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>

/// 获取字符串长度。与string.Length不同的是,该方法将中文作 2 个字符计算。

/// </summary>

/// <param name="str">目标字符串</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 计算长度

int clen = 0;//当前长度

while (clen < l)

{

//每遇到一个中文,则将实际长度加一。

if ((int)str[clen] > 128) { realLen++; }

clen++;

}

#endregion

return realLen;

}

/// <summary>

/// 将形如 10.1MB 格式对用户友好的文件大小字符串还原成真实的文件大小,单位为字节。

/// </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;

//去掉数字分隔符

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>

/// 根据文件夹命名规则验证字符串是否符合文件夹格式

/// </summary>

public static bool IsFolderName(this string folderName)

{

if (IsNullOrEmptyStr(folderName)) { return false; }

else

{

// 不能以 “.” 开头

folderName = folderName.Trim().ToLower();

// “nul”、“aux”、“con”、“com1”、“lpt1”不能为文件夹/文件的名称

// 作为文件夹,只需满足名称不为这几个就行。

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>

/// 根据文件名命名规则验证字符串是否符合文件名格式

/// </summary>

public static bool IsFileName(this string fileName)

{

if (IsNullOrEmptyStr(fileName)) { return false; }

else

{

fileName = fileName.Trim().ToLower();

// 不能以 “.” 开头

// 作为文件名,第一个“.” 之前不能是“nul”、“aux”、“con”、“com1”、“lpt1”

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>

/// 验证是否为合法的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#字符串的常用操作工具类代码分享】相关文章:

C#常用的数据格式转换汇总

C#文件后缀名的详细介绍

C#字符串常见操作总结详解

C# 对XML基本操作代码总结

C# WORD操作实现代码

C#加密解密文件小工具实现代码

c# list部分操作实现代码

C#中一些字符串操作的常用用法

c# 获取网页中指定的字符串信息的实例代码

C# 游戏外挂实现核心代码

精品推荐
分类导航