Converting string to title case - c#
I have a string which contains words in a mixture of upper and lower case characters.
For example: string myData = "a Simple string";
I need to convert the first character of each word (separated by spaces) into upper case. So I want the result as: string myData ="A Simple String";
Is there any easy way to do this? I don't want to split the string and do the conversion (that will be my last resort). Also, it is guaranteed that the strings are in English.
MSDN : TextInfo.ToTitleCase
Make sure that you include: using System.Globalization
string title = "war and peace";
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
title = textInfo.ToTitleCase(title);
Console.WriteLine(title) ; //War And Peace
//When text is ALL UPPERCASE...
title = "WAR AND PEACE" ;
title = textInfo.ToTitleCase(title);
Console.WriteLine(title) ; //WAR AND PEACE
//You need to call ToLower to make it work
title = textInfo.ToTitleCase(title.ToLower());
Console.WriteLine(title) ; //War And Peace
Try this:
string myText = "a Simple string";
string asTitleCase =
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
ToTitleCase(myText.ToLower());
As has already been pointed out, using TextInfo.ToTitleCase might not give you the exact results you want. If you need more control over the output, you could do something like this:
IEnumerable<char> CharsToTitleCase(string s)
{
bool newWord = true;
foreach(char c in s)
{
if(newWord) { yield return Char.ToUpper(c); newWord = false; }
else yield return Char.ToLower(c);
if(c==' ') newWord = true;
}
}
And then use it like so:
var asTitleCase = new string( CharsToTitleCase(myText).ToArray() );
Yet another variation. Based on several tips here I've reduced it to this extension method, which works great for my purposes:
public static string ToTitleCase(this string s) =>
CultureInfo.InvariantCulture.TextInfo.ToTitleCase(s.ToLower());
Personally I tried the TextInfo.ToTitleCase method, but, I don´t understand why it doesn´t work when all chars are upper-cased.
Though I like the util function provided by Winston Smith, let me provide the function I'm currently using:
public static String TitleCaseString(String s)
{
if (s == null) return s;
String[] words = s.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length == 0) continue;
Char firstChar = Char.ToUpper(words[i][0]);
String rest = "";
if (words[i].Length > 1)
{
rest = words[i].Substring(1).ToLower();
}
words[i] = firstChar + rest;
}
return String.Join(" ", words);
}
Playing with some tests strings:
String ts1 = "Converting string to title case in C#";
String ts2 = "C";
String ts3 = "";
String ts4 = " ";
String ts5 = null;
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts1)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts2)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts3)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts4)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts5)));
Giving output:
|Converting String To Title Case In C#|
|C|
||
| |
||
Recently I found a better solution.
If your text contains every letter in uppercase, then TextInfo will not convert it to the proper case. We can fix that by using the lowercase function inside like this:
public static string ConvertTo_ProperCase(string text)
{
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
return myTI.ToTitleCase(text.ToLower());
}
Now this will convert everything that comes in to Propercase.
public static string PropCase(string strText)
{
return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}
Use ToLower() first, and then CultureInfo.CurrentCulture.TextInfo.ToTitleCase on the result to get the correct output.
//---------------------------------------------------------------
// Get title case of a string (every word with leading upper case,
// the rest is lower case)
// i.e: ABCD EFG -> Abcd Efg,
// john doe -> John Doe,
// miXEd CaSING - > Mixed Casing
//---------------------------------------------------------------
public static string ToTitleCase(string str)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
If someone is interested for the solution for Compact Framework :
return String.Join(" ", thestring.Split(' ').Select(i => i.Substring(0, 1).ToUpper() + i.Substring(1).ToLower()).ToArray());
Here's the solution for that problem...
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(txt);
I needed a way to deal with all caps words, and I liked Ricky AH's solution, but I took it a step further to implement it as an extension method. This avoids the step of having to create your array of chars then call ToArray on it explicitly every time - so you can just call it on the string, like so:
usage:
string newString = oldString.ToProper();
code:
public static class StringExtensions
{
public static string ToProper(this string s)
{
return new string(s.CharsToTitleCase().ToArray());
}
public static IEnumerable<char> CharsToTitleCase(this string s)
{
bool newWord = true;
foreach (char c in s)
{
if (newWord) { yield return Char.ToUpper(c); newWord = false; }
else yield return Char.ToLower(c);
if (c == ' ') newWord = true;
}
}
}
I used the above references and a complete solution is:
Use Namespace System.Globalization;
string str = "INFOA2Z means all information";
// Need result like "Infoa2z Means All Information"
// We need to convert the string in lowercase also, otherwise it is not working properly.
TextInfo ProperCase = new CultureInfo("en-US", false).TextInfo;
str = ProperCase.ToTitleCase(str.toLower());
Change string to proper case in an ASP.NET Using C#
Its better to understand by trying your own code...
Read more
http://www.stupidcodes.com/2014/04/convert-string-to-uppercase-proper-case.html
1) Convert a String to Uppercase
string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());
2) Convert a String to Lowercase
string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());
3) Convert a String to TitleCase
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(TextBox1.Text());
String TitleCaseString(String s)
{
if (s == null || s.Length == 0) return s;
string[] splits = s.Split(' ');
for (int i = 0; i < splits.Length; i++)
{
switch (splits[i].Length)
{
case 1:
break;
default:
splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1);
break;
}
}
return String.Join(" ", splits);
}
Without using TextInfo:
public static string TitleCase(this string text, char seperator = ' ') =>
string.Join(seperator, text.Split(seperator).Select(word => new string(
word.Select((letter, i) => i == 0 ? char.ToUpper(letter) : char.ToLower(letter)).ToArray())));
It loops through every letter in each word, converting it to uppercase if it's the first letter otherwise converting it to lowercase.
You can directly change text or string to proper using this simple method, after checking for null or empty string values in order to eliminate errors:
// Text to proper (Title Case):
public string TextToProper(string text)
{
string ProperText = string.Empty;
if (!string.IsNullOrEmpty(text))
{
ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
}
else
{
ProperText = string.Empty;
}
return ProperText;
}
Alternative with reference to Microsoft.VisualBasic (handles uppercase strings too):
string properCase = Strings.StrConv(str, VbStrConv.ProperCase);
Here is an implementation, character by character. It should work with "(One Two Three)":
public static string ToInitcap(this string str)
{
if (string.IsNullOrEmpty(str))
return str;
char[] charArray = new char[str.Length];
bool newWord = true;
for (int i = 0; i < str.Length; ++i)
{
Char currentChar = str[i];
if (Char.IsLetter(currentChar))
{
if (newWord)
{
newWord = false;
currentChar = Char.ToUpper(currentChar);
}
else
{
currentChar = Char.ToLower(currentChar);
}
}
else if (Char.IsWhiteSpace(currentChar))
{
newWord = true;
}
charArray[i] = currentChar;
}
return new string(charArray);
}
Try this:
using System.Globalization;
using System.Threading;
public void ToTitleCase(TextBox TextBoxName)
{
int TextLength = TextBoxName.Text.Length;
if (TextLength == 1)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
TextBoxName.SelectionStart = 1;
}
else if (TextLength > 1 && TextBoxName.SelectionStart < TextLength)
{
int x = TextBoxName.SelectionStart;
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
TextBoxName.SelectionStart = x;
}
else if (TextLength > 1 && TextBoxName.SelectionStart >= TextLength)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
TextBoxName.SelectionStart = TextLength;
}
}
Call this method in the TextChanged event of the TextBox.
This is what I use and it works for most cases unless the user decides to override it by pressing shift or caps lock. Like on Android and iOS keyboards.
Private Class ProperCaseHandler
Private Const wordbreak As String = " ,.1234567890;/\-()#$%^&*€!~+=#"
Private txtProperCase As TextBox
Sub New(txt As TextBox)
txtProperCase = txt
AddHandler txt.KeyPress, AddressOf txtTextKeyDownProperCase
End Sub
Private Sub txtTextKeyDownProperCase(ByVal sender As System.Object, ByVal e As Windows.Forms.KeyPressEventArgs)
Try
If Control.IsKeyLocked(Keys.CapsLock) Or Control.ModifierKeys = Keys.Shift Then
Exit Sub
Else
If txtProperCase.TextLength = 0 Then
e.KeyChar = e.KeyChar.ToString.ToUpper()
e.Handled = False
Else
Dim lastChar As String = txtProperCase.Text.Substring(txtProperCase.SelectionStart - 1, 1)
If wordbreak.Contains(lastChar) = True Then
e.KeyChar = e.KeyChar.ToString.ToUpper()
e.Handled = False
End If
End If
End If
Catch ex As Exception
Exit Sub
End Try
End Sub
End Class
As an extension method:
/// <summary>
// Returns a copy of this string converted to `Title Case`.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The `Title Case` equivalent of the current string.</returns>
public static string ToTitleCase(this string value)
{
string result = string.Empty;
for (int i = 0; i < value.Length; i++)
{
char p = i == 0 ? char.MinValue : value[i - 1];
char c = value[i];
result += char.IsLetter(c) && ((p is ' ') || p is char.MinValue) ? $"{char.ToUpper(c)}" : $"{char.ToLower(c)}";
}
return result;
}
Usage:
"kebab is DELICIOU's ;d c...".ToTitleCase();
Result:
Kebab Is Deliciou's ;d C...
It works fine even with camel case: 'someText in YourPage'
public static class StringExtensions
{
/// <summary>
/// Title case example: 'Some Text In Your Page'.
/// </summary>
/// <param name="text">Support camel and title cases combinations: 'someText in YourPage'</param>
public static string ToTitleCase(this string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
var result = string.Empty;
var splitedBySpace = text.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var sequence in splitedBySpace)
{
// let's check the letters. Sequence can contain even 2 words in camel case
for (var i = 0; i < sequence.Length; i++)
{
var letter = sequence[i].ToString();
// if the letter is Big or it was spaced so this is a start of another word
if (letter == letter.ToUpper() || i == 0)
{
// add a space between words
result += ' ';
}
result += i == 0 ? letter.ToUpper() : letter;
}
}
return result.Trim();
}
}
For the ones who are looking to do it automatically on keypress, I did it with following code in VB.NET on a custom textboxcontrol - you can obviously also do it with a normal textbox - but I like the possibility to add recurring code for specific controls via custom controls it suits the concept of OOP.
Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel
Public Class MyTextBox
Inherits System.Windows.Forms.TextBox
Private LastKeyIsNotAlpha As Boolean = True
Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
If _ProperCasing Then
Dim c As Char = e.KeyChar
If Char.IsLetter(c) Then
If LastKeyIsNotAlpha Then
e.KeyChar = Char.ToUpper(c)
LastKeyIsNotAlpha = False
End If
Else
LastKeyIsNotAlpha = True
End If
End If
MyBase.OnKeyPress(e)
End Sub
Private _ProperCasing As Boolean = False
<Category("Behavior"), Description("When Enabled ensures for automatic proper casing of string"), Browsable(True)>
Public Property ProperCasing As Boolean
Get
Return _ProperCasing
End Get
Set(value As Boolean)
_ProperCasing = value
End Set
End Property
End Class
A way to do it in C:
char proper(char string[])
{
int i = 0;
for(i=0; i<=25; i++)
{
string[i] = tolower(string[i]); // Converts all characters to lower case
if(string[i-1] == ' ') // If the character before is a space
{
string[i] = toupper(string[i]); // Converts characters after spaces to upper case
}
}
string[0] = toupper(string[0]); // Converts the first character to upper case
return 0;
}
Related
Function to return the acronym of a string
How can I write a function which given an input string, passes back the acronym for the string using only If/Then/Else, simple String functions, and Looping syntax (not use the Split( ) function or its equivalent)? String s_input, s_acronym s_input = "Mothers against drunk driving" s_acronym = f_get_acronym(s_input) print "acronym = " + s_acronym /* acronym = MADD */ My code is here. just looking to see if I could get better solution static string f_get_acronym(string s_input) { string s_acronym = ""; for (int i = 0; i < s_input.Length; i++) { if (i == 0 && s_input[i].ToString() != " ") { s_acronym += s_input[i]; continue; } if (s_input[i - 1].ToString() == " " && s_input[i].ToString() != " ") { s_acronym += s_input[i]; } } return s_acronym.ToUpper(); }
Regex is the way to go in C#. I know you only wanted simple functions, but I want to put this here for any further readers who shall be directed on the right path. ;) var regex = new Regex(#"(?:\s*(?<first>\w))\w+"); var matches = regex.Matches("Mother against druck driving"); foreach (Match match in matches) { Console.Write(match.Groups["first"].Value); }
private static string f_get_acronym(string s_input) { if (string.IsNullOrWhiteSpace(s_input)) return string.Empty; string accr = string.Empty; accr += s_input[0]; while (s_input.Length > 0) { int index = s_input.IndexOf(' '); if (index > 0) { s_input = s_input.Substring(index + 1); if (s_input.Length == 0) break; accr += s_input[0]; } else { break; } } return accr.ToUpper(); }
Keep it simple: public static string Acronym(string input) { string result = string.Empty; char last = ' '; foreach(var c in input) { if(char.IsWhiteSpace(last)) { result += c; } last = c; } return result.ToUpper(); } Best practice says you should use a StringBuilder when adding to a string in a loop though. Don't know how long your acronyms are going to be.
Your best way to do so would be to set up a loop to loop over every letter. If it is the first letter in the string, OR the first letter after a space, add that letter to a temp string, which is returned at the end. eg (basic c++) string toAcronym(string sentence) { string acronym = ""; bool wasSpace = true; for (int i = 0; i < sentence.length(); i++) { if (wasSpace == true) { if (sentence[i] != ' ') { wasSpace = false; acronym += toupper(sentence[i]); } else { wasSpace = true; } } else if (sentence[i] == ' ') { wasSpace = true; } } return acronym; } This could be further improved by checking to make sure the letter to add to the acronym is a letter, and not a number / symbol. OR... If it is the first letter in the string, add it to the acronym. Then, run a loop for "find next of" a space. Then, add the next character. Continuously loop the "find next of" space until it returns null / eof / end of string, then return.
How to keep only numbers and some special characters in a string?
I have a string containing regular characters, special characters and numbers. I'm trying to remove the regular characters, just keeping the numbers and the special characters. I use a loop to check if a character is a special character or a number. Then, I replace it with an empty string. However, this doesn't seem to work because I get an error "can't apply != to string or char". My code is below. If possible, please give me some ideas to fix this. Thanks. public string convert_string_to_no(string val) { string str_val = ""; int val_len = val.Length; for (int i = 0; i < val_len; i++) { char myChar = Convert.ToChar(val.Substring(i, 1)); if ((char.IsDigit(myChar) == false) && (myChar != "-")) { str_val = str_val.replace(str_val.substring(i,1),""); } } return str_val; }
you can use regular expressions to do that.its faster than using loop and clean String test ="Q1W2-hjkxas1-EE3R4-5T"; Regex rgx = new Regex("[^0-9-]"); Console.WriteLine(rgx.Replace(test, "")); check the working code here
It seem try to change "-" to '-', and better to construct the string and not replacing the char. public string convert_string_to_no(string val) { string str_val = ""; int val_len = val.Length; for (int i = 0; i < val_len; i++) { char myChar = Convert.ToChar(val.Substring(i, 1)); if (char.IsDigit(myChar) && myChar == '-') { str_val += myChar; } } return str_val; }
I perfer Linq: public static class StringExtensions { public static string ToLimitedString(this string instance, string validCharacters) { // null reference checking... var result = new string(instance .Where(c => validCharacters.Contains(c)) .ToArray()); return result; } } usage: var test ="Q1W2-hjkxas1-EE3R4-5T"; var limited = test.ToLimitedString("01234567890-"); Console.WriteLine(limited); result: 12-1-34-5 DotNetFiddle Example
Using indexOf (C#) to remove a set of characters from a string
public static string shita1(string st1) { string st2 = "", stemp = st1; int i; for(i=0; i<stemp.Length; i++) { if (stemp.IndexOf("cbc") == i) { i += 2 ; stemp = ""; stemp = st1.Substring(i); i = 0; } else st2 = st2 + stemp[i]; } return st2; } static void Main(string[] args) { string st1; Console.WriteLine("enter one string:"); st1 = Console.ReadLine(); Console.WriteLine(shita1(st1)); } } i got a challange from my college, the challange is to move any "cbc" characters from a string... this is my code... it works when i use only one "cbc" but when i use 2 of them it stucks... help please :)
The IndexOf Method gives you everything you need to know. Per the documentation. Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance. This means you can create a loop that repeats as long as the returned index is not -1 and you don't have to loop through the string testing letter by letter.
I think this should work just tested it on some examples. Doesn't use string.Replace or IndexOf static void Main(string[] args) { Console.WriteLine("enter one string:"); var input = Console.ReadLine(); Console.WriteLine(RemoveCBC(input)); } static string RemoveCBC(string source) { var result = new StringBuilder(); for (int i = 0; i < source.Length; i++) { if (i + 2 == source.Length) break; var c = source[i]; var b = source[i + 1]; var c2 = source[i + 2]; if (c == 'c' && c2 == 'c' && b == 'b') i = i + 2; else result.Append(source[i]); } return result.ToString(); }
You can use Replace to remove/replace all occurances of a string inside another string: string original = "cbc_STRING_cbc"; original = original.Replace("cbc", String.Empty);
If you want remove characters from string using only IndexOf method you can use this code. public static string shita1(string st1) { int index = -1; string yourMatchingString = "cbc"; while ((index = st1.IndexOf(yourMatchingString)) != -1) st1 = st1.Remove(index, yourMatchingString.Length); return st1; } This code remove all inputs of you string. But you can do it just in one line: st1 = st1.Replace("cbc", string.Empty); Hope this help.
How to capitalize first letters in each word of RichTextBox.Text?
How can I switch the first letter of each word of RichTextBox.Text to upper case? For example, I need to switch this text: "This is a big and beautiful dog." To this text: "This is a Big And Beautiful Dog". That means I need to capitalize the first letter in the words which include three letters or more. It is difficult for me. Also, there are many lines in RichTextBox.Text.
Try this : System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; richTextBox1.Text = textInfo.ToTitleCase(RichTextBox.Text);
Try this. string[] str = richTextBox1.Text.Split(' '); string a=""; string b=""; for (int i = 0; i < str.Length; i++) { if (str.GetValue(i).ToString().Length > 2) { b = str.GetValue(i).ToString().Replace(str.GetValue(i).ToString().Substring(0, 1), str.GetValue(i).ToString().Substring(0, 1).ToUpper()); } else { b = str.GetValue(i).ToString(); } a = a + " " + b; } richTextBox1.Text = a;
You can capitalize the first letter of each word according to CultureInfo by simply using this: Note: "test" is a sample property as Name, Surname, Address, etc. text = string.IsNullOrEmpty(text) ? string.Empty : CultureInfo .CurrentCulture .TextInfo .ToTitleCase(text.ToLower(new CultureInfo("tr-TR", false))); Please note that, in here there is an extra control for null values.
I have this extension. Note - it makes everything Capitalized, so that eMail will become Email. Good about it - it works on arrays with no concatenations. public static string Capitalize(this string value) { char[] chars = value.ToLower().ToCharArray(); bool isNewWord = true; for (int i = 0; i < chars.Length; i++) { if (char.IsWhiteSpace(chars[i])) { isNewWord = true; continue; } if (isNewWord) { chars[i] = char.Parse(chars[i].ToString().ToUpper()); isNewWord = false; } } return new string(chars); }
Best way to convert Pascal Case to a sentence
What is the best way to convert from Pascal Case (upper Camel Case) to a sentence. For example starting with "AwaitingFeedback" and converting that to "Awaiting feedback" C# preferable but I could convert it from Java or similar.
public static string ToSentenceCase(this string str) { return Regex.Replace(str, "[a-z][A-Z]", 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, "[a-z][A-Z]", m => $"{m.Value[0]} {char.ToLower(m.Value[1])}"); } Based on: Converting Pascal case to sentences using regular expression
I will prefer to use Humanizer for this. Humanizer is a Portable Class Library that meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities. Short Answer "AwaitingFeedback".Humanize() => Awaiting feedback Long and Descriptive Answer Humanizer can do a lot more work other examples are: "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" Complete code is : 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)); } } } Output Awaiting feedback Pascal case input string is turned into sentence Underscored input string is turned into sentence Can Return Title Case can return lower case If you prefer to write your own C# code you can achieve this by writing some C# code stuff as answered by others already.
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(); } } }
This works for me: Regex.Replace(strIn, "([A-Z]{1,2}|[0-9]+)", " $1").TrimStart()
This is just like #SSTA, but is more efficient than calling TrimStart. Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[A-Z])", " $1")
Found this in the MvcContrib source, doesn't seem to be mentioned here yet. return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim();
Just because everyone has been using Regex (except this guy), here's an implementation with StringBuilder that was about 5x faster in my tests. Includes checking for numbers 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's a new word if(char.IsUpper(input[i]) || char.IsDigit(input[i])) sb.Append(' '); // add regularly sb.Append(input[i]); } return sb.ToString(); }
Here's a basic way of doing it 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, "([A-Z][a-z]+)|[0-9]+")) { if (firstWord) { sb.Append(match.ToString()); firstWord = false; } else { sb.Append(" "); sb.Append(match.ToString().ToLower()); } } return sb.ToString(); } It will also split off numbers which I didn't specify but would be useful.
string camel = "MyCamelCaseString"; string s = Regex.Replace(camel, "([A-Z])", " $1").ToLower().Trim(); Console.WriteLine(s.Substring(0,1).ToUpper() + s.Substring(1)); Edit: didn't notice your casing requirements, modifed accordingly. You could use a matchevaluator to do the casing, but I think a substring is easier. You could also wrap it in a 2nd regex replace where you change the first character "^\w" to upper \U (i think)
I'd use a regex, inserting a space before each upper case character, then lowering all the string. string spacedString = System.Text.RegularExpressions.Regex.Replace(yourString, "\B([A-Z])", " \k"); spacedString = spacedString.ToLower();
It is easy to do in JavaScript (or PHP, etc.) where you can define a function in the replace call: var camel = "AwaitingFeedbackDearMaster"; var sentence = camel.replace(/([A-Z].)/g, function (c) { return ' ' + c.toLowerCase(); }); alert(sentence); Although I haven't solved the initial cap problem... :-) Now, for the Java solution: String ToSentence(String camel) { if (camel == null) return ""; // Or null... String[] words = camel.split("(?=[A-Z])"); 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")); Note the trick to split the sentence without loosing any character...
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 Better ways can perhaps be done by using regex or by string replacement routines (replace 'X' with ' x')
An xquery solution that works for both UpperCamel and lowerCamel case: To output sentence case (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, '([A-Z])', ' $1'))) }; To output title case (first character of each word capitalized): declare function content:titleCase($string) { let $firstCharacter := substring($string, 1, 1) let $remainingCharacters := substring-after($string, $firstCharacter) return concat(upper-case($firstCharacter),replace($remainingCharacters, '([A-Z])', ' $1')) };
Found myself doing something similar, and I appreciate having a point-of-departure with this discussion. This is my solution, placed as an extension method to the 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\'s 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(); } } }
Most of the preceding answers split acronyms and numbers, adding a space in front of each character. I wanted acronyms and numbers to be kept together so I have a simple state machine that emits a space every time the input transitions from one state to the other. /// <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's a new word if (!upper && isUpperOrDigit) { sb.Append(' '); } sb.Append(input[i]); upper = isUpperOrDigit; } return sb.ToString(); } And here's some 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); }
Mostly already answered here Small chage to the accepted answer, to convert the second and subsequent Capitalised 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]);
Here is my implementation. This is the fastest that I got while avoiding creating spaces for abbreviations. public static string PascalCaseToSentence(string input) { if (string.IsNullOrEmpty(input) || input.Length < 2) return input; var sb = new char[input.Length + ((input.Length + 1) / 2)]; var len = 0; var lastIsLower = false; for (int i = 0; i < input.Length; i++) { var current = input[i]; if (current < 97) { if (lastIsLower) { sb[len] = ' '; len++; } lastIsLower = false; } else { lastIsLower = true; } sb[len] = current; len++; } return new string(sb, 0, len); }