How to capitalize the first letter in each word in string in c#

10,855

This will help you :

 string inString = "test test2 test test2 test test2";
 TextInfo cultInfo = new CultureInfo("en-US", false).TextInfo;
 string output = cultInfo.ToTitleCase(inString);
 // Test Test2 Test Test2 Test Test2

where CultureInfo belongs to System.Globalization.

Note cultInfo.ToTitleCase("some value"); will work only for a sentence having all small letters, consider an example: input: "this will be an EXAMPLE" then the above code will convert it into "This Will Be An EXAMPLE". that means EXAMPLE remains in the capital. So what we need to do is, make the entire string into the lower case before performing this operation. so the input will be like the following:

 string inString = "test test2 test test2 test test2";
Share:
10,855
Grizzly
Author by

Grizzly

ASP.NET MVC Developer I'm a programmar I'm a programar I'm a programer I write code "The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather in a lack of will.” - Vince Lombardi Towson University Alumni Computer Information Systems & Business Administration: Management Premature optimization is the root of all evils. I love to figure out problems dealing with code, and hope to help fellow coders with their coding issues. #SOReadyToHelp

Updated on June 30, 2022

Comments

  • Grizzly
    Grizzly almost 2 years

    I have tried researching 'Questions that may already have your answer' but none of them really aided in this since most of them deal with different programming languages..

    So in regards to C#, specifically ASP.NET MVC, in my Create action I have the code to capitalize the very first character of the first word in the string, but if the user enters in 2 words, the first character of the 2nd word stays lowercase.

    Here is what I have so far in my Controller

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,text,subcategory")] Activities codeAC)
    {
        if (ModelState.IsValid)
        {
            char firstLetter = codeAC.text[0];
    
            if (char.IsLower(firstLetter))
            {
                codeAC.text = codeAC.text.First().ToString().ToUpper() + String.Join("", codeAC.text.Skip(1));
            }
    

    How do I modify this so that if the user enters in 'test test2' the result being saved into the database would be 'Test Test2', not 'Test test2'?

    Any help is appreciated.