Skip to content

Commit 18fdd7b

Browse files
committed
feat(字符串扩展): 添加将字符串转换为下划线命名法的方法
新增ConvertToUnderLine方法,支持将驼峰命名字符串转换为下划线命名格式,可选择是否转换为大写
1 parent b9e324d commit 18fdd7b

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

GameFrameX.Foundation.Extensions/StringExtensions.cs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,13 +131,41 @@ public static int GetDisplayWidth(this string text)
131131
int total = 0;
132132
foreach (var c in text)
133133
{
134-
var isChineseChar = (c >= '\u4e00' && c <= '\u9fff') || (c >= '\u3400' && c <= '\u4dbf') || (c >= '\u2000' && c <= '\u2a6d');
134+
var isChineseChar = (c >= '\u4e00' && c <= '\u9fff') || (c >= '\u3400' && c <= '\u4dbf') || (c >= '\u2000' && c <= '\u2a6d');
135135
total += isChineseChar ? 2 : 1;
136136
}
137137

138138
return total;
139139
}
140140

141+
/// <summary>
142+
/// 将字符串转换为下划线命名法。
143+
/// </summary>
144+
/// <param name="str">要转换的字符串。</param>
145+
/// <param name="isToUpper">是否将下划线转换为大写。默认值为false。</param>
146+
/// <returns>下划线命名法的字符串。</returns>
147+
/// <exception cref="ArgumentNullException">当str为null时抛出。</exception>
148+
/// <remarks>
149+
/// 此方法将字符串中的每个大写字母前添加下划线,并根据isToUpper参数转换为大写或小写。
150+
/// 例如:"HelloWorld"转换为"hello_world","IsValid"转换为"is_valid"。
151+
/// 当字符串中已包含下划线时,直接返回原字符串。
152+
/// </remarks>
153+
public static string ConvertToUnderLine(string str, bool isToUpper = false)
154+
{
155+
ArgumentNullException.ThrowIfNull(str, nameof(str));
156+
if (str.Contains('_'))
157+
{
158+
return str;
159+
}
160+
161+
if (isToUpper)
162+
{
163+
return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? $"_{x}" : x.ToString())).ToUpper();
164+
}
165+
166+
return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? $"_{x}" : x.ToString())).ToLower();
167+
}
168+
141169
/// <summary>
142170
/// 重复指定字符指定次数。
143171
/// </summary>

0 commit comments

Comments
 (0)