什么是从Pascal Case(上骆驼案)转换为句子的最佳方法.
例如,以.开头
"AwaitingFeedback"
并将其转换为
"Awaiting feedback"
C#更好,但我可以从Java或类似的转换它.
public static string ToSentenceCase(this string str) { return Regex.Replace(str, "[a-z][A-Z]", m => m.Value[0] + " " + char.ToLower(m.Value[1])); }
在2015年之后的视觉工作室版本中,你可以做到
public static string ToSentenceCase(this string str) { return Regex.Replace(str, "[a-z][A-Z]", m => $"{m.Value[0]} {char.ToLower(m.Value[1])}"); }
基于:使用正则表达式将Pascal案例转换为句子
干得好...
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CamelCaseToString { class Program { static void Main(string[] args) { Console.WriteLine(CamelCaseToString("ThisIsYourMasterCallingYou")); } private static string CamelCaseToString(string str) { if (str == null || str.Length == 0) return null; StringBuilder retVal = new StringBuilder(32); retVal.Append(char.ToUpper(str[0])); for (int i = 1; i < str.Length; i++ ) { if (char.IsLower(str[i])) { retVal.Append(str[i]); } else { retVal.Append(" "); retVal.Append(char.ToLower(str[i])); } } return retVal.ToString(); } } }
这对我有用:
Regex.Replace(strIn, "([A-Z]{1,2}|[0-9]+)", " $1").TrimStart()
我更喜欢使用Humanizer.Humanizer是一个可移植类库,可满足您操作和显示字符串,枚举,日期,时间,时间跨度,数字和数量的所有.NET需求.
简答
"AwaitingFeedback".Humanize() => Awaiting feedback
冗长而具描述性的答案
Humanizer可以做更多的工作,其他例子是:
"PascalCaseInputStringIsTurnedIntoSentence".Humanize() => "Pascal case input string is turned into sentence" "Underscored_input_string_is_turned_into_sentence".Humanize() => "Underscored input string is turned into sentence" "Can_return_title_Case".Humanize(LetterCasing.Title) => "Can Return Title Case" "CanReturnLowerCase".Humanize(LetterCasing.LowerCase) => "can return lower case"
完整的代码是:
using Humanizer; using static System.Console; namespace HumanizerConsoleApp { class Program { static void Main(string[] args) { WriteLine("AwaitingFeedback".Humanize()); WriteLine("PascalCaseInputStringIsTurnedIntoSentence".Humanize()); WriteLine("Underscored_input_string_is_turned_into_sentence".Humanize()); WriteLine("Can_return_title_Case".Humanize(LetterCasing.Title)); WriteLine("CanReturnLowerCase".Humanize(LetterCasing.LowerCase)); } } }
产量
等待反馈
Pascal案例输入字符串变成句子
将下划线输入字符串转换为句子可以返回标题大小写
可以返回小写
如果您更喜欢编写自己的C#代码,可以通过编写一些其他人已经回答过的C#代码来实现这一点.
这就像@SSTA,但比调用TrimStart更有效.
Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[A-Z])", " $1")
在MvcContrib源代码中找到了这个,这里似乎没有提到.
return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim();