StringExtensions
StringExtensions 扩展类文档
Section titled “StringExtensions 扩展类文档”StringExtensions 是一个静态扩展类,为 string 类型提供了丰富的扩展方法,包括空值判断、类型验证、类型转换、编码解码、字符串操作、掩码脱敏、格式转换、分割连接等功能,旨在简化字符串处理,提高代码的安全性和可读性,特别是用于处理可能为空的字符串类型的日常操作场景。
主要功能模块
Section titled “主要功能模块”1. 空值判断方法
Section titled “1. 空值判断方法”IsNullOrEmptySafe()- 判断字符串是否为 null 或空字符串IsNullOrWhiteSpaceSafe()- 判断字符串是否为 null 或仅包含空白字符IsNotNullOrEmptySafe()- 判断字符串是否不为空IsNotNullOrWhiteSpaceSafe()- 判断字符串是否不为空白IsNull(string nullStrings, bool isTrim)- 判断字符串是否为空(支持自定义空值判断)
2. 类型判断方法
Section titled “2. 类型判断方法”IsNumeric()- 判断字符串是否为数字IsInt()- 判断字符串是否为整数IsLong()- 判断字符串是否为长整数IsFloat()- 判断字符串是否为浮点数IsDouble()- 判断字符串是否为双精度浮点数IsDecimal()- 判断字符串是否为十进制数IsGuid()- 判断字符串是否为 GuidIsBool()- 判断字符串是否为布尔值IsDateTime()- 判断字符串是否为日期时间IsLetter()- 判断字符串是否仅包含字母IsLetterOrDigit()- 判断字符串是否仅包含字母或数字IsChinese()- 判断字符串是否为中文字符HasChinese()- 判断字符串中是否包含中文IsDigits()- 判断字符串是否为纯数字字符串IsHex()- 判断字符串是否为十六进制字符串
3. 正则表达式验证
Section titled “3. 正则表达式验证”IsEmail()- 验证字符串是否为有效的电子邮件地址IsMobile()- 验证字符串是否为有效的手机号码(中国大陆)IsTel()- 验证字符串是否为有效的固定电话号码IsUrl()- 验证字符串是否为有效的 URLIsIdCard()- 验证字符串是否为有效的身份证号码(中国大陆)IsIpAddress()- 验证字符串是否为有效的 IP 地址IsIPv4()- 验证字符串是否为有效的 IPv4 地址IsIPv6()- 验证字符串是否为有效的 IPv6 地址IsZipCode()- 验证字符串是否为有效的邮政编码IsBankCard()- 验证字符串是否为有效的银行卡号IsJson()- 验证字符串是否为有效的 JSON 格式IsXml()- 验证字符串是否为有效的 XML 格式IsDate()- 验证字符串是否为有效的日期格式IsTime()- 验证字符串是否为有效的时间格式
4. 正则别名方法
Section titled “4. 正则别名方法”IsUrlByRegex()- IsUrl 的别名方法IsDateByRegex()- IsDate 的别名方法IsTimeByRegex()- IsTime 的别名方法IsDateTimeByRegex()- IsDateTime 的别名方法IsLetterByRegex()- IsLetter 的别名方法IsNumByRegex()- IsNumeric 的别名方法ExtractNumByRegex()- ExtractDigits 的别名方法IsFloatByRegex()- IsFloat 的别名方法IsEmailByRegex()- IsEmail 的别名方法IsTelByRegex()- IsTel 的别名方法IsMobileByRegex()- IsMobile 的别名方法
5. 类型转换方法
Section titled “5. 类型转换方法”ToInt(int defaultValue = 0)- 字符串转 int,失败返回默认值ToIntOrNull()- 字符串转可空 int,失败返回 nullToLong(long defaultValue = 0)- 字符串转 long,失败返回默认值ToLongOrNull()- 字符串转可空 long,失败返回 nullToShort(short defaultValue = 0)- 字符串转 short,失败返回默认值ToShortOrNull()- 字符串转可空 short,失败返回 nullToFloat(float defaultValue = 0)- 字符串转 float,失败返回默认值ToFloatOrNull()- 字符串转可空 float,失败返回 nullToFloatRound(int digits = 2, float defaultValue = 0)- 字符串转 float 并四舍五入ToFloatTruncate(int digits = 2, float defaultValue = 0)- 字符串转 float 并截断ToDouble(double defaultValue = 0)- 字符串转 double,失败返回默认值ToDoubleOrNull()- 字符串转可空 double,失败返回 nullToDoubleRound(int digits = 2, double defaultValue = 0)- 字符串转 double 并四舍五入ToDoubleTruncate(int digits = 2, double defaultValue = 0)- 字符串转 double 并截断ToDecimal(decimal defaultValue = 0)- 字符串转 decimal,失败返回默认值ToDecimalOrNull()- 字符串转可空 decimal,失败返回 nullToDecimalRound(int digits = 2, decimal defaultValue = 0)- 字符串转 decimal 并四舍五入ToBool(bool defaultValue = false)- 字符串转 bool,失败返回默认值ToBoolOrNull()- 字符串转可空 bool,失败返回 nullToBoolExtended(string[] trueValues, bool defaultValue = false)- 字符串转 bool(支持多种格式)ToGuid(Guid defaultValue = default)- 字符串转 Guid,失败返回默认值ToGuidOrNull()- 字符串转可空 Guid,失败返回 nullToDateTime(DateTime defaultValue = default)- 字符串转 DateTime,失败返回默认值ToDateTimeOrNull()- 字符串转可空 DateTime,失败返回 nullToDateTimeExact(string format, DateTime defaultValue = default)- 按指定格式转 DateTimeToEnum<TEnum>(TEnum defaultValue, bool ignoreCase = true)- 字符串转枚举ToBytes(Encoding encoding = null)- 字符串转字节数组To<T>(T defaultValue = default)- 字符串转指定类型
6. 编码解码方法
Section titled “6. 编码解码方法”ToBase64(Encoding encoding = null)- 将字符串编码为 Base64FromBase64(Encoding encoding = null)- 将 Base64 字符串解码UrlEncode()- URL 编码UrlDecode()- URL 解码HtmlEncode()- HTML 编码HtmlDecode()- HTML 解码
7. 哈希计算方法
Section titled “7. 哈希计算方法”ToMd5(Encoding encoding = null)- 获取字符串的 MD5 值(32位小写)ToSha256(Encoding encoding = null)- 获取字符串的 SHA256 值ToSha1(Encoding encoding = null)- 获取字符串的 SHA1 值ToHmacSha256(string key, Encoding encoding = null)- 获取字符串的 HMAC-SHA256 值
8. 字符串操作方法
Section titled “8. 字符串操作方法”TrimSafe()- 安全去除字符串首尾空白字符RemoveWhiteSpace()- 移除字符串中的所有空白字符SubstringSafe(int startIndex, int length)- 安全截取字符串Left(int length)- 获取字符串左部指定长度的子串Right(int length)- 获取字符串右部指定长度的子串ReverseSafe()- 反转字符串RemoveSpecialChars()- 移除字符串中的特殊字符RemoveDigits()- 移除字符串中的数字RemoveLetters()- 移除字符串中的字母ExtractDigits()- 提取字符串中的数字部分ExtractLetters()- 提取字符串中的字母部分Truncate(int maxLength, string suffix = "...")- 截断字符串到指定长度Repeat(int count)- 重复字符串指定次数Capitalize()- 将字符串首字母大写Uncapitalize()- 将字符串首字母小写EqualsIgnoreCase(string compare)- 忽略大小写判断字符串是否相等ContainsIgnoreCase(string substring)- 忽略大小写判断是否包含子串StartsWithIgnoreCase(string prefix)- 忽略大小写判断是否以指定前缀开头EndsWithIgnoreCase(string suffix)- 忽略大小写判断是否以指定后缀结尾ReplaceIgnoreCase(string oldValue, string newValue)- 忽略大小写替换字符串KeepDecimal(int digits = 2)- 保留字符串中的小数位数
9. 掩码与脱敏方法
Section titled “9. 掩码与脱敏方法”Mask(int startLength = 3, int endLength = 4, char maskChar = '*')- 对字符串进行掩码处理MaskMobile()- 对手机号码进行脱敏MaskEmail()- 对邮箱地址进行脱敏MaskIdCard()- 对身份证号码进行脱敏MaskBankCard()- 对银行卡号进行脱敏MaskName()- 对姓名进行脱敏
10. 格式转换方法
Section titled “10. 格式转换方法”ToCamelCase()- 转为 camelCase(驼峰命名)ToPascalCase()- 转为 PascalCase(帕斯卡命名)ToSnakeCase()- 转为 snake_case(蛇形命名)ToKebabCase()- 转为 kebab-case(短横线命名)ToConstantCase()- 转为 UPPER_SNAKE_CASE(常量命名)
11. 分割与连接方法
Section titled “11. 分割与连接方法”SplitSafe(string separator = ",", StringSplitOptions options = None)- 按字符串分隔符分割SplitSafe(char separator, StringSplitOptions options = None)- 按字符分隔符分割SplitToIntArray(string separator = ",")- 分割并转换为整数数组SplitToArray<T>(string separator = ",")- 分割并转换为泛型数组JoinString(IEnumerable<string> values, string separator = ",")- 连接字符串集合JoinString<T>(IEnumerable<T> values, string separator = ",")- 连接对象集合
12. 其他实用方法
Section titled “12. 其他实用方法”IfNullOrEmpty(string defaultValue)- 为空时返回默认值IfNullOrWhiteSpace(string defaultValue)- 为空白时返回默认值GetByteLength(Encoding encoding = null)- 获取字符串的字节长度IsLike(string pattern)- 判断是否匹配通配符模式ToSafeFileName(char replacement = '_')- 转换为安全的文件名ToSafeUrlPath(char replacement = '-')- 转换为安全的 URL 路径
方法详细说明
Section titled “方法详细说明”IsNullOrEmptySafe
Section titled “IsNullOrEmptySafe”判断字符串是否为 null 或空字符串。
public static bool IsNullOrEmptySafe(this string value)参数:
value: 待判断的字符串
返回值: 如果字符串为 null 或空字符串,返回 true;否则返回 false
示例:
string str1 = null;string str2 = "";string str3 = "hello";
bool result1 = str1.IsNullOrEmptySafe(); // truebool result2 = str2.IsNullOrEmptySafe(); // truebool result3 = str3.IsNullOrEmptySafe(); // falseIsNullOrWhiteSpaceSafe
Section titled “IsNullOrWhiteSpaceSafe”判断字符串是否为 null 或仅包含空白字符。
public static bool IsNullOrWhiteSpaceSafe(this string value)参数:
value: 待判断的字符串
返回值: 如果字符串为 null 或仅包含空白字符,返回 true;否则返回 false
示例:
string str1 = null;string str2 = " ";string str3 = "hello";
bool result1 = str1.IsNullOrWhiteSpaceSafe(); // truebool result2 = str2.IsNullOrWhiteSpaceSafe(); // truebool result3 = str3.IsNullOrWhiteSpaceSafe(); // falseIsNotNullOrEmptySafe
Section titled “IsNotNullOrEmptySafe”判断字符串是否不为空(非 null 且非空字符串)。
public static bool IsNotNullOrEmptySafe(this string value)参数:
value: 待判断的字符串
返回值: 如果字符串不为 null 且不为空字符串,返回 true;否则返回 false
示例:
string str1 = null;string str2 = "hello";
bool result1 = str1.IsNotNullOrEmptySafe(); // falsebool result2 = str2.IsNotNullOrEmptySafe(); // trueIsNotNullOrWhiteSpaceSafe
Section titled “IsNotNullOrWhiteSpaceSafe”判断字符串是否不为空白(非 null 且包含非空白字符)。
public static bool IsNotNullOrWhiteSpaceSafe(this string value)参数:
value: 待判断的字符串
返回值: 如果字符串不为 null 且包含非空白字符,返回 true;否则返回 false
示例:
string str1 = " ";string str2 = "hello";
bool result1 = str1.IsNotNullOrWhiteSpaceSafe(); // falsebool result2 = str2.IsNotNullOrWhiteSpaceSafe(); // trueIsNull
Section titled “IsNull”判断字符串是否为空(支持自定义空值判断)。
public static bool IsNull(this string value, string nullStrings = "null|{}|[]", bool isTrim = false)参数:
value: 源字符串nullStrings: 自定义空字符串,使用 ”|” 分隔,默认为 “null||[]”isTrim: 是否移除首尾空白字符后再判断,默认为 false
返回值: 如果字符串为空或匹配自定义空字符串,返回 true;否则返回 false
示例:
string str1 = "null";string str2 = "{}";string str3 = "hello";
bool result1 = str1.IsNull(); // truebool result2 = str2.IsNull(); // truebool result3 = str3.IsNull(); // false
bool result4 = " null ".IsNull(isTrim: true); // trueIsNumeric
Section titled “IsNumeric”判断字符串是否为数字(可解析为 double)。
public static bool IsNumeric(this string value)参数:
value: 待判断的字符串
返回值: 如果字符串可以解析为 double,返回 true;否则返回 false
示例:
string str1 = "123.45";string str2 = "abc";
bool result1 = str1.IsNumeric(); // truebool result2 = str2.IsNumeric(); // false判断字符串是否为整数。
public static bool IsInt(this string value)参数:
value: 待判断的字符串
返回值: 如果字符串可以解析为 int,返回 true;否则返回 false
示例:
"123".IsInt(); // true"123.45".IsInt(); // falseIsLong
Section titled “IsLong”判断字符串是否为长整数。
public static bool IsLong(this string value)示例:
"123456789012".IsLong(); // true"abc".IsLong(); // falseIsFloat
Section titled “IsFloat”判断字符串是否为浮点数(float)。
public static bool IsFloat(this string value)示例:
"123.45".IsFloat(); // true"abc".IsFloat(); // falseIsDouble
Section titled “IsDouble”判断字符串是否为双精度浮点数(double)。
public static bool IsDouble(this string value)示例:
"123.45".IsDouble(); // true"abc".IsDouble(); // falseIsDecimal
Section titled “IsDecimal”判断字符串是否为十进制数(decimal)。
public static bool IsDecimal(this string value)示例:
"123.45".IsDecimal(); // true"abc".IsDecimal(); // falseIsGuid
Section titled “IsGuid”判断字符串是否为 Guid。
public static bool IsGuid(this string value)示例:
"d3b07384-d9a6-4e0b-9d7e-5b5a5b5a5b5a".IsGuid(); // true"not-a-guid".IsGuid(); // falseIsBool
Section titled “IsBool”判断字符串是否为布尔值。
public static bool IsBool(this string value)示例:
"true".IsBool(); // true"false".IsBool(); // true"yes".IsBool(); // falseIsDateTime
Section titled “IsDateTime”判断字符串是否为日期时间。
public static bool IsDateTime(this string value)示例:
"2024-01-01".IsDateTime(); // true"not-a-date".IsDateTime(); // falseIsLetter
Section titled “IsLetter”判断字符串是否仅包含字母(a-z、A-Z)。
public static bool IsLetter(this string value)示例:
"Hello".IsLetter(); // true"Hello1".IsLetter(); // falseIsLetterOrDigit
Section titled “IsLetterOrDigit”判断字符串是否仅包含字母或数字。
public static bool IsLetterOrDigit(this string value)示例:
"Hello123".IsLetterOrDigit(); // true"Hello 123".IsLetterOrDigit(); // false(包含空格)IsChinese
Section titled “IsChinese”判断字符串是否为中文字符。
public static bool IsChinese(this string value)示例:
"你好世界".IsChinese(); // true"Hello".IsChinese(); // falseHasChinese
Section titled “HasChinese”判断字符串中是否包含中文。
public static bool HasChinese(this string value)示例:
"Hello你好".HasChinese(); // true"Hello".HasChinese(); // falseIsDigits
Section titled “IsDigits”判断字符串是否为纯数字字符串(仅包含 0-9)。
public static bool IsDigits(this string value)示例:
"12345".IsDigits(); // true"123.45".IsDigits(); // false(包含小数点)判断字符串是否为十六进制字符串。
public static bool IsHex(this string value)示例:
"1A2B3C".IsHex(); // true"1G2H".IsHex(); // false正则表达式验证
Section titled “正则表达式验证”IsEmail
Section titled “IsEmail”验证字符串是否为有效的电子邮件地址。
public static bool IsEmail(this string value)示例:
"test@example.com".IsEmail(); // true"invalid-email".IsEmail(); // falseIsMobile
Section titled “IsMobile”验证字符串是否为有效的手机号码(中国大陆)。
public static bool IsMobile(this string value)示例:
"13812345678".IsMobile(); // true"12345678901".IsMobile(); // false验证字符串是否为有效的固定电话号码。
public static bool IsTel(this string value)示例:
"010-12345678".IsTel(); // true"0755-87654321".IsTel(); // true"12345".IsTel(); // false验证字符串是否为有效的 URL。
public static bool IsUrl(this string value)示例:
"https://www.example.com".IsUrl(); // true"ftp://invalid".IsUrl(); // falseIsIdCard
Section titled “IsIdCard”验证字符串是否为有效的身份证号码(中国大陆,支持 15 位和 18 位)。
public static bool IsIdCard(this string value)示例:
"11010519900307233X".IsIdCard(); // true"123456789012345".IsIdCard(); // falseIsIpAddress
Section titled “IsIpAddress”验证字符串是否为有效的 IP 地址(IPv4 或 IPv6)。
public static bool IsIpAddress(this string value)示例:
"192.168.1.1".IsIpAddress(); // true"2001:0db8:85a3::8a2e:0370:7334".IsIpAddress(); // true"invalid".IsIpAddress(); // falseIsIPv4
Section titled “IsIPv4”验证字符串是否为有效的 IPv4 地址。
public static bool IsIPv4(this string value)示例:
"192.168.1.1".IsIPv4(); // true"::1".IsIPv4(); // falseIsIPv6
Section titled “IsIPv6”验证字符串是否为有效的 IPv6 地址。
public static bool IsIPv6(this string value)示例:
"::1".IsIPv6(); // true"192.168.1.1".IsIPv6(); // falseIsZipCode
Section titled “IsZipCode”验证字符串是否为有效的邮政编码(中国大陆,6 位数字)。
public static bool IsZipCode(this string value)示例:
"100000".IsZipCode(); // true"12345".IsZipCode(); // falseIsBankCard
Section titled “IsBankCard”验证字符串是否为有效的银行卡号(使用 Luhn 算法)。
public static bool IsBankCard(this string value)示例:
"6222021234567890123".IsBankCard(); // 视具体卡号而定"123456".IsBankCard(); // false(长度不足)IsJson
Section titled “IsJson”验证字符串是否为有效的 JSON 格式。
public static bool IsJson(this string value)示例:
"{\"name\":\"test\"}".IsJson(); // true"[1,2,3]".IsJson(); // true"not json".IsJson(); // false验证字符串是否为有效的 XML 格式。
public static bool IsXml(this string value)示例:
"<root><item>test</item></root>".IsXml(); // true"not xml".IsXml(); // falseIsDate
Section titled “IsDate”验证字符串是否为有效的日期格式。
public static bool IsDate(this string value)示例:
"2024-01-01".IsDate(); // true"not-a-date".IsDate(); // falseIsTime
Section titled “IsTime”验证字符串是否为有效的时间格式(HH:mm:ss)。
public static bool IsTime(this string value)示例:
"14:30:00".IsTime(); // true"25:00:00".IsTime(); // false正则别名方法
Section titled “正则别名方法”以下方法是对应验证方法的别名,内部直接调用对应方法,用于兼容旧版 API。
IsUrlByRegex
Section titled “IsUrlByRegex”IsUrl 的别名方法。
public static bool IsUrlByRegex(this string value)IsDateByRegex
Section titled “IsDateByRegex”IsDate 的别名方法。
public static bool IsDateByRegex(this string value)IsTimeByRegex
Section titled “IsTimeByRegex”IsTime 的别名方法。
public static bool IsTimeByRegex(this string value)IsDateTimeByRegex
Section titled “IsDateTimeByRegex”IsDateTime 的别名方法。
public static bool IsDateTimeByRegex(this string value)IsLetterByRegex
Section titled “IsLetterByRegex”IsLetter 的别名方法。
public static bool IsLetterByRegex(this string value)IsNumByRegex
Section titled “IsNumByRegex”IsNumeric 的别名方法。
public static bool IsNumByRegex(this string value)ExtractNumByRegex
Section titled “ExtractNumByRegex”ExtractDigits 的别名方法。
public static string ExtractNumByRegex(this string value)IsFloatByRegex
Section titled “IsFloatByRegex”IsFloat 的别名方法。
public static bool IsFloatByRegex(this string value)IsEmailByRegex
Section titled “IsEmailByRegex”IsEmail 的别名方法。
public static bool IsEmailByRegex(this string value)IsTelByRegex
Section titled “IsTelByRegex”IsTel 的别名方法。
public static bool IsTelByRegex(this string value)IsMobileByRegex
Section titled “IsMobileByRegex”IsMobile 的别名方法。
public static bool IsMobileByRegex(this string value)将字符串转换为整数,转换失败返回默认值。
public static int ToInt(this string value, int defaultValue = 0)参数:
value: 待转换的字符串defaultValue: 转换失败时的默认值,默认为 0
返回值: 转换后的 int 值,失败时返回默认值
示例:
"123".ToInt(); // 123"abc".ToInt(); // 0"abc".ToInt(-1); // -1ToIntOrNull
Section titled “ToIntOrNull”将字符串转换为可空整数,转换失败返回 null。
public static int? ToIntOrNull(this string value)示例:
"123".ToIntOrNull(); // 123"abc".ToIntOrNull(); // nullToLong
Section titled “ToLong”将字符串转换为长整数,转换失败返回默认值。
public static long ToLong(this string value, long defaultValue = 0)示例:
"123456789012".ToLong(); // 123456789012"abc".ToLong(); // 0ToLongOrNull
Section titled “ToLongOrNull”将字符串转换为可空长整数,转换失败返回 null。
public static long? ToLongOrNull(this string value)示例:
"123456789012".ToLongOrNull(); // 123456789012"abc".ToLongOrNull(); // nullToShort
Section titled “ToShort”将字符串转换为短整数,转换失败返回默认值。
public static short ToShort(this string value, short defaultValue = 0)示例:
"123".ToShort(); // 123"abc".ToShort(); // 0ToShortOrNull
Section titled “ToShortOrNull”将字符串转换为可空短整数,转换失败返回 null。
public static short? ToShortOrNull(this string value)示例:
"123".ToShortOrNull(); // 123"abc".ToShortOrNull(); // nullToFloat
Section titled “ToFloat”将字符串转换为单精度浮点数,转换失败返回默认值。
public static float ToFloat(this string value, float defaultValue = 0)示例:
"123.45".ToFloat(); // 123.45f"abc".ToFloat(); // 0fToFloatOrNull
Section titled “ToFloatOrNull”将字符串转换为可空单精度浮点数,转换失败返回 null。
public static float? ToFloatOrNull(this string value)示例:
"123.45".ToFloatOrNull(); // 123.45f"abc".ToFloatOrNull(); // nullToFloatRound
Section titled “ToFloatRound”将字符串转换为单精度浮点数并保留指定小数位(四舍五入)。
public static float ToFloatRound(this string value, int digits = 2, float defaultValue = 0)参数:
value: 待转换的字符串digits: 保留的小数位数,默认为 2defaultValue: 转换失败时的默认值
示例:
"123.4567".ToFloatRound(2); // 123.46f"123.4567".ToFloatRound(0); // 123fToFloatTruncate
Section titled “ToFloatTruncate”将字符串转换为单精度浮点数并截断到指定小数位。
public static float ToFloatTruncate(this string value, int digits = 2, float defaultValue = 0)参数:
value: 待转换的字符串digits: 保留的小数位数,默认为 2defaultValue: 转换失败时的默认值
示例:
"123.4567".ToFloatTruncate(2); // 123.45f"123.4567".ToFloatTruncate(0); // 123fToDouble
Section titled “ToDouble”将字符串转换为双精度浮点数,转换失败返回默认值。
public static double ToDouble(this string value, double defaultValue = 0)示例:
"123.45".ToDouble(); // 123.45"abc".ToDouble(); // 0ToDoubleOrNull
Section titled “ToDoubleOrNull”将字符串转换为可空双精度浮点数,转换失败返回 null。
public static double? ToDoubleOrNull(this string value)示例:
"123.45".ToDoubleOrNull(); // 123.45"abc".ToDoubleOrNull(); // nullToDoubleRound
Section titled “ToDoubleRound”将字符串转换为双精度浮点数并保留指定小数位(四舍五入)。
public static double ToDoubleRound(this string value, int digits = 2, double defaultValue = 0)示例:
"123.4567".ToDoubleRound(2); // 123.46"123.4567".ToDoubleRound(0); // 123ToDoubleTruncate
Section titled “ToDoubleTruncate”将字符串转换为双精度浮点数并截断到指定小数位。
public static double ToDoubleTruncate(this string value, int digits = 2, double defaultValue = 0)示例:
"123.4567".ToDoubleTruncate(2); // 123.45"123.4567".ToDoubleTruncate(0); // 123ToDecimal
Section titled “ToDecimal”将字符串转换为十进制数,转换失败返回默认值。
public static decimal ToDecimal(this string value, decimal defaultValue = 0)示例:
"123.45".ToDecimal(); // 123.45m"abc".ToDecimal(); // 0mToDecimalOrNull
Section titled “ToDecimalOrNull”将字符串转换为可空十进制数,转换失败返回 null。
public static decimal? ToDecimalOrNull(this string value)示例:
"123.45".ToDecimalOrNull(); // 123.45m"abc".ToDecimalOrNull(); // nullToDecimalRound
Section titled “ToDecimalRound”将字符串转换为十进制数并保留指定小数位(四舍五入)。
public static decimal ToDecimalRound(this string value, int digits = 2, decimal defaultValue = 0)示例:
"123.4567".ToDecimalRound(2); // 123.46m"123.4567".ToDecimalRound(0); // 123mToBool
Section titled “ToBool”将字符串转换为布尔值,转换失败返回默认值。
public static bool ToBool(this string value, bool defaultValue = false)示例:
"true".ToBool(); // true"false".ToBool(); // false"yes".ToBool(); // false(标准 bool 解析不支持 yes)ToBoolOrNull
Section titled “ToBoolOrNull”将字符串转换为可空布尔值,转换失败返回 null。
public static bool? ToBoolOrNull(this string value)示例:
"true".ToBoolOrNull(); // true"yes".ToBoolOrNull(); // nullToBoolExtended
Section titled “ToBoolExtended”将字符串转换为布尔值(支持多种格式)。
public static bool ToBoolExtended(this string value, string[] trueValues = null, bool defaultValue = false)参数:
value: 待转换的字符串trueValues: 被视为 true 的字符串数组,默认包含 “true”, “1”, “yes”, “on”, “y”, “是”, “真”, “开启”defaultValue: 转换失败时的默认值
示例:
"yes".ToBoolExtended(); // true"1".ToBoolExtended(); // true"是".ToBoolExtended(); // true"no".ToBoolExtended(); // falseToGuid
Section titled “ToGuid”将字符串转换为 Guid,转换失败返回默认值。
public static Guid ToGuid(this string value, Guid defaultValue = default)示例:
"d3b07384-d9a6-4e0b-9d7e-5b5a5b5a5b5a".ToGuid(); // 对应的 Guid"invalid".ToGuid(); // Guid.EmptyToGuidOrNull
Section titled “ToGuidOrNull”将字符串转换为可空 Guid,转换失败返回 null。
public static Guid? ToGuidOrNull(this string value)示例:
"d3b07384-d9a6-4e0b-9d7e-5b5a5b5a5b5a".ToGuidOrNull(); // 对应的 Guid"invalid".ToGuidOrNull(); // nullToDateTime
Section titled “ToDateTime”将字符串转换为日期时间,转换失败返回默认值。
public static DateTime ToDateTime(this string value, DateTime defaultValue = default)示例:
"2024-01-01".ToDateTime(); // 2024-01-01 00:00:00"invalid".ToDateTime(); // DateTime.MinValue"invalid".ToDateTime(DateTime.Now); // DateTime.NowToDateTimeOrNull
Section titled “ToDateTimeOrNull”将字符串转换为可空日期时间,转换失败返回 null。
public static DateTime? ToDateTimeOrNull(this string value)示例:
"2024-01-01".ToDateTimeOrNull(); // 2024-01-01 00:00:00"invalid".ToDateTimeOrNull(); // nullToDateTimeExact
Section titled “ToDateTimeExact”将字符串按指定格式转换为日期时间。
public static DateTime ToDateTimeExact(this string value, string format, DateTime defaultValue = default)参数:
value: 待转换的字符串format: 日期时间格式字符串defaultValue: 转换失败时的默认值
示例:
"20240101".ToDateTimeExact("yyyyMMdd"); // 2024-01-01 00:00:00"2024-01-01".ToDateTimeExact("yyyyMMdd"); // DateTime.MinValue(格式不匹配)ToEnum<TEnum>
Section titled “ToEnum<TEnum>”将字符串转换为枚举类型,转换失败返回默认值。
public static TEnum ToEnum<TEnum>(this string value, TEnum defaultValue = default, bool ignoreCase = true) where TEnum : struct, Enum参数:
value: 待转换的字符串defaultValue: 转换失败时的默认值ignoreCase: 是否忽略大小写,默认为 true
示例:
enum Status { Active, Inactive }
"Active".ToEnum<Status>(); // Status.Active"active".ToEnum<Status>(); // Status.Active(忽略大小写)"invalid".ToEnum<Status>(); // Status.Active(默认值)ToBytes
Section titled “ToBytes”将字符串转换为字节数组。
public static byte[] ToBytes(this string value, Encoding encoding = null)参数:
value: 待转换的字符串encoding: 编码方式,默认为 UTF-8
示例:
"Hello".ToBytes(); // UTF-8 字节数组"Hello".ToBytes(Encoding.ASCII); // ASCII 字节数组将字符串转换为指定类型的对象。
public static T To<T>(this string value, T defaultValue = default)参数:
value: 待转换的字符串defaultValue: 转换失败时的默认值
示例:
"123".To<int>(); // 123"123.45".To<double>(); // 123.45"true".To<bool>(); // true"invalid".To<int>(-1); // -1ToBase64
Section titled “ToBase64”将字符串编码为 Base64 字符串。
public static string ToBase64(this string value, Encoding encoding = null)参数:
value: 待编码的字符串encoding: 编码方式,默认为 UTF-8
示例:
"Hello World".ToBase64(); // "SGVsbG8gV29ybGQ="FromBase64
Section titled “FromBase64”将 Base64 字符串解码为原始字符串。
public static string FromBase64(this string value, Encoding encoding = null)参数:
value: Base64 编码的字符串encoding: 编码方式,默认为 UTF-8
示例:
"SGVsbG8gV29ybGQ=".FromBase64(); // "Hello World"UrlEncode
Section titled “UrlEncode”将字符串进行 URL 编码。
public static string UrlEncode(this string value)示例:
"Hello World".UrlEncode(); // "Hello+World"UrlDecode
Section titled “UrlDecode”将 URL 编码的字符串解码。
public static string UrlDecode(this string value)示例:
"Hello+World".UrlDecode(); // "Hello World"HtmlEncode
Section titled “HtmlEncode”将字符串进行 HTML 编码。
public static string HtmlEncode(this string value)示例:
"<div>Test</div>".HtmlEncode(); // "<div>Test</div>"HtmlDecode
Section titled “HtmlDecode”将 HTML 编码的字符串解码。
public static string HtmlDecode(this string value)示例:
"<div>Test</div>".HtmlDecode(); // "<div>Test</div>"计算字符串的 MD5 哈希值。
public static string ToMd5(this string value, Encoding encoding = null)参数:
value: 待计算的字符串encoding: 编码方式,默认为 UTF-8
返回值: MD5 哈希值(32位小写十六进制字符串)
示例:
"Hello World".ToMd5(); // "ed076283755c9dbb52404a7f7f8c9a0b"ToSha256
Section titled “ToSha256”计算字符串的 SHA256 哈希值。
public static string ToSha256(this string value, Encoding encoding = null)返回值: SHA256 哈希值(64位小写十六进制字符串)
示例:
"Hello World".ToSha256(); // "a591a6d40bf420404a011733cfb0b43e..."ToSha1
Section titled “ToSha1”计算字符串的 SHA1 哈希值。
public static string ToSha1(this string value, Encoding encoding = null)返回值: SHA1 哈希值(40位小写十六进制字符串)
示例:
"Hello World".ToSha1(); // "2aae6c35c94fc8849305f59..."ToHmacSha256
Section titled “ToHmacSha256”计算字符串的 HMAC-SHA256 哈希值。
public static string ToHmacSha256(this string value, string key, Encoding encoding = null)参数:
value: 待计算的字符串key: 密钥encoding: 编码方式,默认为 UTF-8
返回值: HMAC-SHA256 哈希值(小写十六进制字符串)
示例:
"Hello World".ToHmacSha256("secret-key"); // HMAC-SHA256 哈希值TrimSafe
Section titled “TrimSafe”安全去除字符串首尾空白字符,null 返回空字符串。
public static string TrimSafe(this string value)示例:
" Hello ".TrimSafe(); // "Hello"string str = null;str.TrimSafe(); // ""RemoveWhiteSpace
Section titled “RemoveWhiteSpace”移除字符串中的所有空白字符。
public static string RemoveWhiteSpace(this string value)示例:
"Hello World 123".RemoveWhiteSpace(); // "HelloWorld123"SubstringSafe
Section titled “SubstringSafe”安全截取字符串,超出范围返回空字符串或部分字符串。
public static string SubstringSafe(this string value, int startIndex, int length)参数:
value: 源字符串startIndex: 起始索引length: 截取长度
示例:
"Hello World".SubstringSafe(0, 5); // "Hello""Hello World".SubstringSafe(6, 100); // "World""Hello".SubstringSafe(10, 5); // ""获取字符串左侧指定长度的子串。
public static string Left(this string value, int length)示例:
"Hello World".Left(5); // "Hello""Hi".Left(10); // "Hi"获取字符串右侧指定长度的子串。
public static string Right(this string value, int length)示例:
"Hello World".Right(5); // "World""Hi".Right(10); // "Hi"ReverseSafe
Section titled “ReverseSafe”反转字符串。
public static string ReverseSafe(this string value)示例:
"Hello".ReverseSafe(); // "olleH"RemoveSpecialChars
Section titled “RemoveSpecialChars”移除字符串中的特殊字符,仅保留字母、数字和空白。
public static string RemoveSpecialChars(this string value)示例:
"Hello, World! 123".RemoveSpecialChars(); // "Hello World 123"RemoveDigits
Section titled “RemoveDigits”移除字符串中的数字。
public static string RemoveDigits(this string value)示例:
"Hello123World456".RemoveDigits(); // "HelloWorld"RemoveLetters
Section titled “RemoveLetters”移除字符串中的字母。
public static string RemoveLetters(this string value)示例:
"Hello123World456".RemoveLetters(); // "123456"ExtractDigits
Section titled “ExtractDigits”提取字符串中的数字部分。
public static string ExtractDigits(this string value)示例:
"Price: $123.45".ExtractDigits(); // "12345"ExtractLetters
Section titled “ExtractLetters”提取字符串中的字母部分。
public static string ExtractLetters(this string value)示例:
"Hello123World".ExtractLetters(); // "HelloWorld"Truncate
Section titled “Truncate”截断字符串到指定长度,超出部分用后缀替代。
public static string Truncate(this string value, int maxLength, string suffix = "...")参数:
value: 源字符串maxLength: 最大长度suffix: 后缀字符串,默认为 ”…”
示例:
"Hello World".Truncate(8); // "Hello...""Hello".Truncate(10); // "Hello""Hello World".Truncate(8, "!"); // "Hello W!"Repeat
Section titled “Repeat”重复字符串指定次数。
public static string Repeat(this string value, int count)示例:
"Abc".Repeat(3); // "AbcAbcAbc""Hi".Repeat(0); // ""Capitalize
Section titled “Capitalize”将字符串首字母大写。
public static string Capitalize(this string value)示例:
"hello".Capitalize(); // "Hello""HELLO".Capitalize(); // "HELLO"Uncapitalize
Section titled “Uncapitalize”将字符串首字母小写。
public static string Uncapitalize(this string value)示例:
"Hello".Uncapitalize(); // "hello""HELLO".Uncapitalize(); // "hELLO"EqualsIgnoreCase
Section titled “EqualsIgnoreCase”忽略大小写判断字符串是否相等。
public static bool EqualsIgnoreCase(this string value, string compare)示例:
"Hello".EqualsIgnoreCase("hello"); // true"Hello".EqualsIgnoreCase("HELLO"); // true"Hello".EqualsIgnoreCase("World"); // falseContainsIgnoreCase
Section titled “ContainsIgnoreCase”忽略大小写判断字符串是否包含指定子串。
public static bool ContainsIgnoreCase(this string value, string substring)示例:
"Hello World".ContainsIgnoreCase("HELLO"); // true"Hello World".ContainsIgnoreCase("WORLD"); // trueStartsWithIgnoreCase
Section titled “StartsWithIgnoreCase”忽略大小写判断字符串是否以指定前缀开头。
public static bool StartsWithIgnoreCase(this string value, string prefix)示例:
"Hello World".StartsWithIgnoreCase("hello"); // true"Hello World".StartsWithIgnoreCase("HELLO"); // trueEndsWithIgnoreCase
Section titled “EndsWithIgnoreCase”忽略大小写判断字符串是否以指定后缀结尾。
public static bool EndsWithIgnoreCase(this string value, string suffix)示例:
"Hello World".EndsWithIgnoreCase("world"); // true"Hello World".EndsWithIgnoreCase("WORLD"); // trueReplaceIgnoreCase
Section titled “ReplaceIgnoreCase”忽略大小写替换字符串中的所有匹配项。
public static string ReplaceIgnoreCase(this string value, string oldValue, string newValue)示例:
"Hello World Hello".ReplaceIgnoreCase("hello", "Hi"); // "Hi World Hi"KeepDecimal
Section titled “KeepDecimal”保留字符串中的小数位数(格式化)。
public static string KeepDecimal(this string value, int digits = 2)示例:
"123.4567".KeepDecimal(2); // "123.46""123".KeepDecimal(2); // "123.00""abc".KeepDecimal(2); // "abc"(非数字原样返回)对字符串进行掩码处理(保留首尾,中间用指定字符替换)。
public static string Mask(this string value, int startLength = 3, int endLength = 4, char maskChar = '*')参数:
value: 源字符串startLength: 保留开头的字符数,默认为 3endLength: 保留结尾的字符数,默认为 4maskChar: 掩码字符,默认为 ’*’
示例:
"13812345678".Mask(3, 4); // "138****5678""13812345678".Mask(3, 4, '#'); // "138####5678"MaskMobile
Section titled “MaskMobile”对手机号码进行脱敏处理。
public static string MaskMobile(this string value)示例:
"13812345678".MaskMobile(); // "138****5678"MaskEmail
Section titled “MaskEmail”对邮箱地址进行脱敏处理。
public static string MaskEmail(this string value)示例:
"testuser@example.com".MaskEmail(); // "te***@example.com""ab@example.com".MaskEmail(); // "a***@example.com"MaskIdCard
Section titled “MaskIdCard”对身份证号码进行脱敏处理。
public static string MaskIdCard(this string value)示例:
"11010519900307233X".MaskIdCard(); // "110***********233X"MaskBankCard
Section titled “MaskBankCard”对银行卡号进行脱敏处理。
public static string MaskBankCard(this string value)示例:
"6222021234567890123".MaskBankCard(); // "6222************0123"MaskName
Section titled “MaskName”对姓名进行脱敏处理。
public static string MaskName(this string value)示例:
"张三".MaskName(); // "张*""李四五".MaskName(); // "李**""王".MaskName(); // "王"ToCamelCase
Section titled “ToCamelCase”将字符串转换为 camelCase(驼峰命名)。
public static string ToCamelCase(this string value)示例:
"HelloWorld".ToCamelCase(); // "helloWorld""hello_world".ToCamelCase(); // "helloWorld""hello-world".ToCamelCase(); // "helloWorld""Hello World".ToCamelCase(); // "helloWorld"ToPascalCase
Section titled “ToPascalCase”将字符串转换为 PascalCase(帕斯卡命名)。
public static string ToPascalCase(this string value)示例:
"helloWorld".ToPascalCase(); // "HelloWorld""hello_world".ToPascalCase(); // "HelloWorld""hello-world".ToPascalCase(); // "HelloWorld"ToSnakeCase
Section titled “ToSnakeCase”将字符串转换为 snake_case(蛇形命名)。
public static string ToSnakeCase(this string value)示例:
"HelloWorld".ToSnakeCase(); // "hello_world""hello-world".ToSnakeCase(); // "hello_world""Hello World".ToSnakeCase(); // "hello_world"ToKebabCase
Section titled “ToKebabCase”将字符串转换为 kebab-case(短横线命名)。
public static string ToKebabCase(this string value)示例:
"HelloWorld".ToKebabCase(); // "hello-world""hello_world".ToKebabCase(); // "hello-world""Hello World".ToKebabCase(); // "hello-world"ToConstantCase
Section titled “ToConstantCase”将字符串转换为常量命名(UPPER_SNAKE_CASE)。
public static string ToConstantCase(this string value)示例:
"HelloWorld".ToConstantCase(); // "HELLO_WORLD""hello-world".ToConstantCase(); // "HELLO_WORLD"SplitSafe
Section titled “SplitSafe”将字符串按指定分隔符分割为数组。
public static string[] SplitSafe(this string value, string separator = ",", StringSplitOptions options = StringSplitOptions.None)public static string[] SplitSafe(this string value, char separator, StringSplitOptions options = StringSplitOptions.None)参数:
value: 待分割的字符串separator: 分隔符,默认为逗号options: 分割选项
示例:
"a,b,c".SplitSafe(","); // ["a", "b", "c"]"a,,c".SplitSafe(",", StringSplitOptions.RemoveEmptyEntries); // ["a", "c"]"1|2|3".SplitSafe('|'); // ["1", "2", "3"]SplitToIntArray
Section titled “SplitToIntArray”将字符串按指定分隔符分割并转换为整数数组。
public static int[] SplitToIntArray(this string value, string separator = ",")示例:
"1,2,3".SplitToIntArray(); // [1, 2, 3]"1|2|3".SplitToIntArray("|"); // [1, 2, 3]SplitToArray<T>
Section titled “SplitToArray<T>”将字符串按指定分隔符分割并转换为泛型数组。
public static T[] SplitToArray<T>(this string value, string separator = ",") where T : IConvertible示例:
"1.1,2.2,3.3".SplitToArray<double>(); // [1.1, 2.2, 3.3]"true,false,true".SplitToArray<bool>(); // [true, false, true]JoinString
Section titled “JoinString”使用指定分隔符连接字符串集合。
public static string JoinString(this IEnumerable<string> values, string separator = ",")public static string JoinString<T>(this IEnumerable<T> values, string separator = ",")示例:
new[] { "a", "b", "c" }.JoinString(","); // "a,b,c"new[] { 1, 2, 3 }.JoinString("-"); // "1-2-3"其他实用方法
Section titled “其他实用方法”IfNullOrEmpty
Section titled “IfNullOrEmpty”如果字符串为 null 或空,返回指定默认值。
public static string IfNullOrEmpty(this string value, string defaultValue)示例:
string str = null;str.IfNullOrEmpty("N/A"); // "N/A""hello".IfNullOrEmpty("N/A"); // "hello"IfNullOrWhiteSpace
Section titled “IfNullOrWhiteSpace”如果字符串为 null 或空白,返回指定默认值。
public static string IfNullOrWhiteSpace(this string value, string defaultValue)示例:
" ".IfNullOrWhiteSpace("N/A"); // "N/A""hello".IfNullOrWhiteSpace("N/A"); // "hello"GetByteLength
Section titled “GetByteLength”获取字符串的字节长度(按指定编码计算)。
public static int GetByteLength(this string value, Encoding encoding = null)参数:
value: 待计算的字符串encoding: 编码方式,默认为 UTF-8
示例:
"Hello".GetByteLength(); // 5(UTF-8)"你好".GetByteLength(); // 6(UTF-8,每个中文字符3字节)"你好".GetByteLength(Encoding.Unicode); // 4(Unicode,每个中文字符2字节)IsLike
Section titled “IsLike”判断字符串是否匹配指定通配符模式。
public static bool IsLike(this string value, string pattern)参数:
value: 待判断的字符串pattern: 通配符模式(*表示任意多个字符,?表示单个字符)
示例:
"Hello World".IsLike("Hello*"); // true"Hello World".IsLike("H?llo*"); // true"Hello World".IsLike("*World"); // true"Hello World".IsLike("Hi*"); // falseToSafeFileName
Section titled “ToSafeFileName”将字符串转换为安全的文件名(移除无效字符)。
public static string ToSafeFileName(this string value, char replacement = '_')参数:
value: 待处理的字符串replacement: 替换字符,默认为下划线
示例:
"My File: Test<1>.txt".ToSafeFileName(); // "My File_ Test_1_.txt""My/File".ToSafeFileName('-'); // "My-File"ToSafeUrlPath
Section titled “ToSafeUrlPath”将字符串转换为安全的 URL 路径(移除无效字符)。
public static string ToSafeUrlPath(this string value, char replacement = '-')参数:
value: 待处理的字符串replacement: 替换字符,默认为短横线
示例:
"Hello World!".ToSafeUrlPath(); // "hello-world""My Blog Post".ToSafeUrlPath(); // "my-blog-post"- 表单验证 - 验证用户输入的格式是否正确(如邮箱、手机号、身份证等)
- 数据转换 - 安全地将字符串转换为各种数值类型
- 字符串处理 - 截取、拼接、格式化等操作
- 数据清洗 - 移除特殊字符、空白字符等预处理
- 格式验证 - 验证数据是否符合特定格式要求
- 文本分析 - 判断文本内容类型(中文、数字、字母等)
- 安全处理 - 避免 null 异常的安全字符串操作
- 编码转换 - 字符串与各种编码格式之间的相互转换
- 数据脱敏 - 对敏感信息(手机号、身份证、银行卡等)进行掩码处理
- 命名转换 - 在不同命名规范(驼峰、蛇形、短横线等)之间转换
- 数据分割连接 - 将字符串分割为数组或将集合连接为字符串
- 安全路径 - 生成安全的文件名和 URL 路径
- 所有方法都是扩展方法,需要通过
string实例调用 - 带有 “Safe” 后缀的方法对 null 值做了安全处理,不会抛出异常
- 类型转换方法在转换失败时返回指定的默认值,而不是抛出异常
- 正则表达式验证方法使用预编译的正则模式进行格式验证
- 数值约束方法支持四舍五入和截取两种小数处理方式
- 字符串操作方法支持边界检查,避免越界异常
- 哈希计算方法默认使用 UTF-8 编码进行字节转换
- 中文判断方法对 Unicode 字符范围进行识别
- 自定义空字符串判断支持多空值配置
- 所有方法都进行了空值有效性检查
- 正则别名方法(ByRegex 后缀)是对应方法的别名,内部直接调用对应方法
- 掩码脱敏方法默认使用
*作为掩码字符 - 格式转换方法支持多种分隔符(下划线、短横线、空格、大小写)的自动识别