How to make a first letter capital in C#

后端 未结 12 1164
攒了一身酷
攒了一身酷 2020-12-05 23:52

How can the first letter in a text be set to capital?

Example:

it is a text.  = It is a text.
相关标签:
12条回答
  • 2020-12-05 23:54

    It'll be something like this:

    // precondition: before must not be an empty string
    
    String after = before.Substring(0, 1).ToUpper() + before.Substring(1);
    
    0 讨论(0)
  • 2020-12-05 23:55
    public static string ToUpperFirstLetter(this string source)
    {
        if (string.IsNullOrEmpty(source))
            return string.Empty;
        // convert to char array of the string
        char[] letters = source.ToCharArray();
        // upper case the first char
        letters[0] = char.ToUpper(letters[0]);
        // return the array made of the new char array
        return new string(letters);
    }
    
    0 讨论(0)
  • 2020-12-05 23:57

    this functions makes capital the first letter of all words in a string

    public static string FormatSentence(string source)
        {
            var words = source.Split(' ').Select(t => t.ToCharArray()).ToList();
            words.ForEach(t =>
            {
                for (int i = 0; i < t.Length; i++)
                {
                    t[i] = i.Equals(0) ? char.ToUpper(t[i]) : char.ToLower(t[i]);
                }
            });
            return string.Join(" ", words.Select(t => new string(t)));;
        }
    
    0 讨论(0)
  • 2020-12-05 23:58
    text = new String(
        new [] { char.ToUpper(text.First()) }
        .Concat(text.Skip(1))
        .ToArray()
    );
    
    0 讨论(0)
  • string str = "it is a text";
    

    // first use the .Trim() method to get rid of all the unnecessary space at the begining and the end for exemple (" This string ".Trim() is gonna output "This string").

    str = str.Trim();
    

    char theFirstLetter = str[0]; // this line is to take the first letter of the string at index 0.

    theFirstLetter.ToUpper(); // .ToTupper() methode to uppercase the firstletter.

    str = theFirstLetter + str.substring(1); // we add the first letter that we uppercased and add the rest of the string by using the str.substring(1) (str.substring(1) to skip the first letter at index 0 and only print the letters from the index 1 to the last index.) Console.WriteLine(str); // now it should output "It is a text"

    0 讨论(0)
  • 2020-12-05 23:59

    Take the first letter out of the word and then extract it to the other string.

    strFirstLetter = strWord.Substring(0, 1).ToUpper();
    strFullWord = strFirstLetter + strWord.Substring(1);
    
    0 讨论(0)
提交回复
热议问题