.NET-如何将以"大写"分隔的字符串拆分为数组?
时间:2020-03-06 14:57:02 来源:igfitidea点击:
我如何从以下字符串开始:" ThisIsMyCapsDelimitedString"
...到此字符串:"这是我用大写字母分隔的字符串"
首选使用VB.net中最少的代码行,但也欢迎Cis。
干杯!
解决方案
可能有一个更优雅的解决方案,但这就是我想出的办法:
string myString = "ThisIsMyCapsDelimitedString"; for (int i = 1; i < myString.Length; i++) { if (myString[i].ToString().ToUpper() == myString[i].ToString()) { myString = myString.Insert(i, " "); i++; } }
除了格兰特·瓦格纳(Grant Wagner)的出色评论:
Dim s As String = RegularExpressions.Regex.Replace("ThisIsMyCapsDelimitedString", "([A-Z])", " ")
string s = "ThisIsMyCapsDelimitedString"; string t = Regex.Replace(s, "([A-Z])", " ").Substring(1);
Regex.Replace("ThisIsMyCapsDelimitedString", "(\B[A-Z])", " ")
天真的正则表达式解决方案。将不处理O'Conner,并在字符串的开头也添加一个空格。
s = "ThisIsMyCapsDelimitedString" split = Regex.Replace(s, "[A-Z0-9]", " $&");
只是为了一点点变化...这是一个不使用正则表达式的扩展方法。
public static class CamelSpaceExtensions { public static string SpaceCamelCase(this String input) { return new string(InsertSpacesBeforeCaps(input).ToArray()); } private static IEnumerable<char> InsertSpacesBeforeCaps(IEnumerable<char> input) { foreach (char c in input) { if (char.IsUpper(c)) { yield return ' '; } yield return c; } } }
我前一阵子做了。它与CamelCase名称的每个组成部分匹配。
/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g
例如:
"SimpleHTTPServer" => ["Simple", "HTTP", "Server"] "camelCase" => ["camel", "Case"]
要将其转换为仅在单词之间插入空格:
Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", " ")
如果我们需要处理数字:
/([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g Regex.Replace(s,"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))"," ")
要获得更多变化,请使用普通的旧Cobject,以下命令将产生与@MizardX出色的正则表达式相同的输出。
public string FromCamelCase(string camel) { // omitted checking camel for null StringBuilder sb = new StringBuilder(); int upperCaseRun = 0; foreach (char c in camel) { // append a space only if we're not at the start // and we're not already in an all caps string. if (char.IsUpper(c)) { if (upperCaseRun == 0 && sb.Length != 0) { sb.Append(' '); } upperCaseRun++; } else if( char.IsLower(c) ) { if (upperCaseRun > 1) //The first new word will also be capitalized. { sb.Insert(sb.Length - 1, ' '); } upperCaseRun = 0; } else { upperCaseRun = 0; } sb.Append(c); } return sb.ToString(); }
很好的答案,MizardX!我进行了一些微调,将数字视为单独的单词,以便" AddressLine1"将变为" Address Line 1",而不是" Address Line1":
Regex.Replace(s, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", " ")