The best way to turn a Pascal case into a proposal

What is the best way to convert from Case Pascal (top case of a camel) to a sentence.

For example, starting with

"AwaitingFeedback" 

and transforming it into

 "Awaiting feedback" 

C # is preferable, but I could convert it from Java or similar.

+66
string c #
Nov 27 '08 at 9:30
source share
16 answers
 public static string ToSentenceCase(this string str) { return Regex.Replace(str, "[az][AZ]", m => m.Value[0] + " " + char.ToLower(m.Value[1])); } 

In versions of visual studio after 2015, you can do

 public static string ToSentenceCase(this string str) { return Regex.Replace(str, "[az][AZ]", m => $"{m.Value[0]} {char.ToLower(m.Value[1])}"); } 

Based: Convert Pascal case to sentences using regular expression

+64
Jul 31 '09 at 9:04
source share

Here you go ...

 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(); } } } 
+15
Nov 27 '08 at 9:42
source share

This works for me:

 Regex.Replace(strIn, "([AZ]{1,2}|[0-9]+)", " $1").TrimStart() 
+15
May 28 '10 at 5:45
source share

I prefer to use Humanizer for this. Humanizer is a portable class library that meets all your .NET needs for managing and displaying strings, enumerations, dates, times, time intervals, numbers and quantities.

Short answer

 "AwaitingFeedback".Humanize() => Awaiting feedback 

Long and descriptive answer

Humanizer can do a lot more work, other examples:

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

Full code:

 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)); } } } 

Exit

Waiting for feedback

Pascal register input string turns into a sentence

An underlined input string turns into a sentence.

can return lower case

If you prefer to write your own C # code, you can achieve this by writing some of the C # code, as others have already answered.

+9
May 28 '16 at 16:14
source share

It's like @SSTA, but more efficient than calling TrimStart.

 Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[AZ])", " $1") 
+8
Jun 06 2018-12-06T00:
source share

This is discovered in the source of MvcContrib, not yet mentioned here.

 return Regex.Replace(input, "([AZ])", " $1", RegexOptions.Compiled).Trim(); 
+8
Jul 11 2018-12-12T00:
source share

Here is the main way to do this that I came up with using regex

 public static string CamelCaseToSentence(this string value) { var sb = new StringBuilder(); var firstWord = true; foreach (var match in Regex.Matches(value, "([AZ][az]+)|[0-9]+")) { if (firstWord) { sb.Append(match.ToString()); firstWord = false; } else { sb.Append(" "); sb.Append(match.ToString().ToLower()); } } return sb.ToString(); } 

It will also separate numbers that I did not specify, but would be useful.

+4
Nov 27 '08 at 9:48
source share

I would use a regex by inserting a space before each uppercase character and then dropping the whole line.

  string spacedString = System.Text.RegularExpressions.Regex.Replace(yourString, "\B([AZ])", " \k"); spacedString = spacedString.ToLower(); 
+2
Nov 27 '08 at 9:41
source share

This is easy to do in JavaScript (or PHP, etc.) where you can define a function in a replace call:

 var camel = "AwaitingFeedbackDearMaster"; var sentence = camel.replace(/([AZ].)/g, function (c) { return ' ' + c.toLowerCase(); }); alert(sentence); 

Although I did not solve the problem with the initial cache ... :-)

Now for the Java solution:

 String ToSentence(String camel) { if (camel == null) return ""; // Or null... String[] words = camel.split("(?=[AZ])"); if (words == null) return ""; if (words.length == 1) return words[0]; StringBuilder sentence = new StringBuilder(camel.length()); if (words[0].length() > 0) // Just in case of camelCase instead of CamelCase { sentence.append(words[0] + " " + words[1].toLowerCase()); } else { sentence.append(words[1]); } for (int i = 2; i < words.length; i++) { sentence.append(" " + words[i].toLowerCase()); } return sentence.toString(); } System.out.println(ToSentence("AwaitingAFeedbackDearMaster")); System.out.println(ToSentence(null)); System.out.println(ToSentence("")); System.out.println(ToSentence("A")); System.out.println(ToSentence("Aaagh!")); System.out.println(ToSentence("stackoverflow")); System.out.println(ToSentence("disableGPS")); System.out.println(ToSentence("Ahh89Boo")); System.out.println(ToSentence("ABC")); 

Pay attention to the trick to split the sentence without losing the character ...

+2
Nov 27 '08 at 9:44
source share
 string camel = "MyCamelCaseString"; string s = Regex.Replace(camel, "([AZ])", " $1").ToLower().Trim(); Console.WriteLine(s.Substring(0,1).ToUpper() + s.Substring(1)); 

Edit: did not notice your casing requirements, changed accordingly. You can use matchevaluator to create a wrapper, but I think the substring is simpler. You can also wrap it in a second regular expression replacement, where you change the first character

 "^\w" 

to the top

 \U (i think) 
+2
Nov 27 '08 at 10:00
source share

Pseudo Code:

 NewString = ""; Loop through every char of the string (skip the first one) If char is upper-case ('A'-'Z') NewString = NewString + ' ' + lowercase(char) Else NewString = NewString + char 

Perhaps more efficient methods can be used with regular expressions or line replacement routines (replace "X" with "x")

+1
Nov 27 '08 at 9:38
source share

The xquery solution, which works both in the case of UpperCamel and in the lower camera:

To display a sentence (only the first character of the first word is capitalized):

 declare function content:sentenceCase($string) { let $firstCharacter := substring($string, 1, 1) let $remainingCharacters := substring-after($string, $firstCharacter) return concat(upper-case($firstCharacter),lower-case(replace($remainingCharacters, '([AZ])', ' $1'))) }; 

To display a heading (the first character of each headword):

 declare function content:titleCase($string) { let $firstCharacter := substring($string, 1, 1) let $remainingCharacters := substring-after($string, $firstCharacter) return concat(upper-case($firstCharacter),replace($remainingCharacters, '([AZ])', ' $1')) }; 
+1
Oct 13 '09 at 0:21
source share

I found something similar to myself, and I am very grateful that he was in this discussion. This is my solution put as an extension method in a string class in the context of a console application.

 using System; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string piratese = "avastTharMatey"; string ivyese = "CheerioPipPip"; Console.WriteLine("{0}\n{1}\n", piratese.CamelCaseToString(), ivyese.CamelCaseToString()); Console.WriteLine("For Pete\ sake, man, hit ENTER!"); string strExit = Console.ReadLine(); } } public static class StringExtension { public static string CamelCaseToString(this string str) { StringBuilder retVal = new StringBuilder(32); if (!string.IsNullOrEmpty(str)) { string strTrimmed = str.Trim(); if (!string.IsNullOrEmpty(strTrimmed)) { retVal.Append(char.ToUpper(strTrimmed[0])); if (strTrimmed.Length > 1) { for (int i = 1; i < strTrimmed.Length; i++) { if (char.IsUpper(strTrimmed[i])) retVal.Append(" "); retVal.Append(char.ToLower(strTrimmed[i])); } } } } return retVal.ToString(); } } } 
+1
Feb 14 '15 at 21:31
source share

Just because everyone used Regex (except for this guy ), here is an implementation with StringBuilder which was about 5 times faster in my tests. Includes room verification too.

 "SomeBunchOfCamelCase2".FromCamelCaseToSentence == "Some Bunch Of Camel Case 2" public static string FromCamelCaseToSentence(this string input) { if(string.IsNullOrEmpty(input)) return input; var sb = new StringBuilder(); // start with the first character -- consistent camelcase and pascal case sb.Append(char.ToUpper(input[0])); // march through the rest of it for(var i = 1; i < input.Length; i++) { // any time we hit an uppercase OR number, it a new word if(char.IsUpper(input[i]) || char.IsDigit(input[i])) sb.Append(' '); // add regularly sb.Append(input[i]); } return sb.ToString(); } 
+1
Jul 12 '18 at 16:45
source share

Mostly already answered here

Small chage to the accepted answer to convert the second and subsequent capital letters to lower case, so change

 if (char.IsUpper(text[i])) newText.Append(' '); newText.Append(text[i]); 

to

 if (char.IsUpper(text[i])) { newText.Append(' '); newText.Append(char.ToLower(text[i])); } else newText.Append(text[i]); 
0
Nov 27 '08 at 10:39
source share

Most of the previous answers break down abbreviations and numbers, adding a space before each character. I wanted the abbreviations and numbers to be together, so I have a simple state machine that emits a space every time the input goes from one state to another.

  /// <summary> /// Add a space before any capitalized letter (but not for a run of capitals or numbers) /// </summary> internal static string FromCamelCaseToSentence(string input) { if (string.IsNullOrEmpty(input)) return String.Empty; var sb = new StringBuilder(); bool upper = true; for (var i = 0; i < input.Length; i++) { bool isUpperOrDigit = char.IsUpper(input[i]) || char.IsDigit(input[i]); // any time we transition to upper or digits, it a new word if (!upper && isUpperOrDigit) { sb.Append(' '); } sb.Append(input[i]); upper = isUpperOrDigit; } return sb.ToString(); } 

And here are a few tests:

  [TestCase(null, ExpectedResult = "")] [TestCase("", ExpectedResult = "")] [TestCase("ABC", ExpectedResult = "ABC")] [TestCase("abc", ExpectedResult = "abc")] [TestCase("camelCase", ExpectedResult = "camel Case")] [TestCase("PascalCase", ExpectedResult = "Pascal Case")] [TestCase("Pascal123", ExpectedResult = "Pascal 123")] [TestCase("CustomerID", ExpectedResult = "Customer ID")] [TestCase("CustomABC123", ExpectedResult = "Custom ABC123")] public string CanSplitCamelCase(string input) { return FromCamelCaseToSentence(input); } 
0
Jun 23 '19 at 21:56 on
source share



All Articles