Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I uppercase the first letter of all words in my string?

Tags:

c#

regex

First, all my cities were returned as UPPERCASE, so I switched them to lowercase. How can I get the first letter as uppercase now? Thanks for any help!

List<string> cities = new List<string>();

foreach (DataRow row in dt.Rows)
{
    cities.Add(row[0].ToString().ToLower());

    **ADDED THIS BUT NOTHING HAPPENED**
     CultureInfo.CurrentCulture.TextInfo.ToTitleCase(row[0] as string);
}

return cities;
like image 203
Trey Copeland Avatar asked Jan 23 '12 14:01

Trey Copeland


People also ask

How do you capitalize all words in a string?

We can capitalize each word of a string by the help of split() and substring() methods. By the help of split("\\s") method, we can get all words in an array. To get the first character, we can use substring() or charAt() method.

How do you capitalize every first letter in python?

Python has the upper() method for uppercasing strings. When used on a string, it converts all the letters to uppercase. To use the upper() method to convert only the first letter, we need additional operations. First, we need to select the first letter, then apply the upper() method to it.

How can I uppercase the first letter of a string in Java?

In order to pick the first letter, we have to pass two parameters (0, 1) in the substring() method that denotes the first letter of the string and for capitalizing the first letter, we have invoked the toUpperCase() method. For the rest of the string, we again called the substring() method and pass 1 as a parameter.


1 Answers

Use the TextInfo.ToTitleCase method:

System.Globalization.TextInfo.ToTitleCase();

A bit from the MSDN example, modified to work with OP's code:

// Defines the string with mixed casing.
string myString = row[0] as String;

// Creates a TextInfo based on the "en-US" culture.
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;

// Retrieve a titlecase'd version of the string.
string myCity = myTI.ToTitleCase(myString);

All in one line:

string myCity = new CultureInfo("en-US", false).TextInfo.ToTitleCase(row[0] as String);
like image 150
Nahydrin Avatar answered Sep 29 '22 12:09

Nahydrin