Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize the first character of each word, or the first character of a whole string, with C#?

I could write my own algorithm to do it, but I feel there should be the equivalent to ruby's humanize in C#.

I googled it but only found ways to humanize dates.

Examples:

  • A way to turn "Lorem Lipsum Et" into "Lorem lipsum et"
  • A way to turn "Lorem lipsum et" into "Lorem Lipsum Et"
like image 523
marcgg Avatar asked May 26 '09 22:05

marcgg


People also ask

How do you capitalize the first character of each word in a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.

How do you capitalize the first letter of each word in a string in C?

Today we will learn how to code a C program on how to Capitalize first and last letter of each word of a string i.e. to convert first and last letter of each word into uppercase . We will use toupper() function in the process. The toupper() function is used to convert lowercase alphabet to uppercase.


1 Answers

As discussed in the comments of @miguel's answer, you can use TextInfo.ToTitleCase which has been available since .NET 1.1. Here is some code corresponding to your example:

string lipsum1 = "Lorem lipsum et";  // Creates a TextInfo based on the "en-US" culture. TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;  // Changes a string to titlecase. Console.WriteLine("\"{0}\" to titlecase: {1}",                    lipsum1,                    textInfo.ToTitleCase( lipsum1 ));   // Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et 

It will ignore casing things that are all caps such as "LOREM LIPSUM ET" because it is taking care of cases if acronyms are in text so that "IEEE" (Institute of Electrical and Electronics Engineers) won't become "ieee" or "Ieee".

However if you only want to capitalize the first character you can do the solution that is over here… or you could just split the string and capitalize the first one in the list:

string lipsum2 = "Lorem Lipsum Et";  string lipsum2lower = textInfo.ToLower(lipsum2);  string[] lipsum2split = lipsum2lower.Split(' ');  bool first = true;  foreach (string s in lipsum2split) {     if (first)     {         Console.Write("{0} ", textInfo.ToTitleCase(s));         first = false;     }     else     {         Console.Write("{0} ", s);     } }  // Will output: Lorem lipsum et  
like image 135
Spoike Avatar answered Oct 02 '22 18:10

Spoike