How to capitalize the first letter of a string in C#?

beginer
beginer
1544 Points
52 Posts

How to capitalize the first letter of a string in C#?

Views: 415
Total Answered: 2
Total Marked As Answer: 0
Posted On: 28-Jul-2023 05:32

Share:   fb twitter linkedin
Answers
Priya
Priya
1096 Points
29 Posts
         

try something:

private static string PascalCase(string input)
        {
            //return input;
            if (input.Contains("_"))
            {
                string[] words = input.Split('_');
                return string.Join("", words.Select(w => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(w)));
            }
            else
            {
                if (input.Length == 1)
                    return char.ToUpper(input[0]).ToString();
                else
                    return char.ToUpper(input[0]) + input.Substring(1);
            }
        }
Posted On: 31-Jul-2023 22:43
chatGPT
chatGPT
92 Points
0 Posts
         

We can capitalize the first letter of a string using several methods. Here are a few different ways to achieve this:

  1. Using ToUpper and Substring methods:
    string input = "hello world";
    string capitalized = input.Substring(0, 1).ToUpper() + input.Substring(1);
    Console.WriteLine(capitalized); // Output: "Hello world"
  2. Using TextInfo from System.Globalization:
    using System.Globalization;

    string input = "hello world";
    TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
    string capitalized = textInfo.ToTitleCase(input);
    Console.WriteLine(capitalized); // Output: "Hello World"
  3. Using StringBuilder (useful for larger strings where performance matters):
    using System.Text;

    string input = "hello world";
    StringBuilder sb = new StringBuilder(input);
    sb[0] = char.ToUpper(sb[0]);
    string capitalized = sb.ToString();
    Console.WriteLine(capitalized); // Output: "Hello world"

These methods will capitalize the first letter of the string without modifying the rest of the string. Choose the one that suits your needs best based on your specific use case.

 

Posted On: 31-Jul-2023 22:56
 Log In to Chat