32

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

Example:

it is a text.  = It is a text.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    Can the string be something like `"99c waffles"` and you want to get `"99c Waffles"`? That is, what is your definition of "first letter"? – polygenelubricants Aug 13 '10 at 06:09
  • 1
    possible duplicate of [Make first letter of a string upper case](http://stackoverflow.com/questions/4135317/make-first-letter-of-a-string-upper-case) – Jeroen Jan 24 '14 at 10:36

14 Answers14

57
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);
}
Greg
  • 23,155
  • 11
  • 57
  • 79
vikmalhotra
  • 9,981
  • 20
  • 97
  • 137
45

It'll be something like this:

// precondition: before must not be an empty string

String after = before.Substring(0, 1).ToUpper() + before.Substring(1);
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • @Danny: let's discuss your comment here http://stackoverflow.com/questions/3474578/what-is-the-performance-of-substring-in-net – polygenelubricants Aug 13 '10 at 06:55
  • 2
    .NET is also slow. C++ or assembler is much faster. Does that mean we need to drop .NET and move to faster languages? – Vladislav Rastrusny Aug 13 '10 at 07:06
  • 18
    @Danny: Substring makes the code simple. I prefer to write simple code first, and then optimize with more complicated code *only where necessary*. – Jon Skeet Aug 13 '10 at 07:44
20

polygenelubricants' answer is fine for most cases, but you potentially need to think about cultural issues. Do you want this capitalized in a culture-invariant way, in the current culture, or a specific culture? It can make a big difference in Turkey, for example. So you may want to consider:

CultureInfo culture = ...;
text = char.ToUpper(text[0], culture) + text.Substring(1);

or if you prefer methods on String:

CultureInfo culture = ...;
text = text.Substring(0, 1).ToUpper(culture) + text.Substring(1);

where culture might be CultureInfo.InvariantCulture, or the current culture etc.

For more on this problem, see the Turkey Test.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

If you are sure that str variable is valid (never an empty-string or null), try:

str = Char.ToUpper(str[0]) + str[1..];

Unlike the other solutions that use Substring, this one does not do additional string allocations. This example basically concatenates char with ReadOnlySpan<char>.

UPDATE

Actually str[1..] returns string. According to the documentation it uses internally Substring() to do that. https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1831

In order to make it allocation free, use the following line:

str = string.Concat(new ReadOnlySpan<char>(Char.ToUpper(str[0])), str.AsSpan()[1..]);
4

I use this variant:

 private string FirstLetterCapital(string str)
        {
            return Char.ToUpper(str[0]) + str.Remove(0, 1);            
        }
P-P
  • 41
  • 3
4

If you are using C# then try this code:

Microsoft.VisualBasic.StrConv(sourceString, Microsoft.VisualBasic.vbProperCase)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ritesh Choudhary
  • 772
  • 1
  • 4
  • 12
  • 5
    This is ugly. If your using C#, why would you be importing/referencing the Visual Basic DLL? – Alastair Pitts Aug 13 '10 at 06:11
  • 6
    @steven: You can use VB libraries from C#. – Jon Skeet Aug 13 '10 at 07:44
  • 1
    Microsoft.VisualBasic.Strings.StrConv("hello", VbStrConv.ProperCase); – haroonxml Sep 02 '17 at 13:44
  • It's wrong anyway. This capitalizes every word, not just the first. Here's the VB function in action [Try it online!](https://tio.run/##JcwxCsMwDEDRuT6FyGRDnUuEQocGChk6y4kGgZGLJZve3g3t9OEPr7M2zDGh8h6FLPa0j7GWo2WCu9taghVZfHCXpYiWTPOrstGDhfxm9ZzdT2zACghGH5unK/T0rOVNdUGlENxNDjilX//0GF8 "Visual Basic .NET (VBC) – Try It Online") – General Grievance Aug 06 '21 at 01:06
2
text = new String(
    new [] { char.ToUpper(text.First()) }
    .Concat(text.Skip(1))
    .ToArray()
);
Matt Mills
  • 8,692
  • 6
  • 40
  • 64
  • @Jon Skeet - That was entirely my intent :) I was actually wondering what the performance would be compared to the substring method above. – Matt Mills Aug 13 '10 at 06:40
1

I realize this is an old post, but I recently had this problem and solved it with the following method.

    private string capSentences(string str)
    {
        string s = "";

        if (str[str.Length - 1] == '.')
            str = str.Remove(str.Length - 1, 1);

        char[] delim = { '.' };

        string[] tokens = str.Split(delim);

        for (int i = 0; i < tokens.Length; i++)
        {
            tokens[i] = tokens[i].Trim();

            tokens[i] = char.ToUpper(tokens[i][0]) + tokens[i].Substring(1);

            s += tokens[i] + ". ";
        } 

        return s;
    }

In the sample below clicking on the button executes this simple code outBox.Text = capSentences(inBox.Text.Trim()); which pulls the text from the upper box and puts it in the lower box after the above method runs on it.

Sample Program

user1934286
  • 1,732
  • 3
  • 23
  • 42
1

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
    static String UppercaseWords(String BadName)
    {
        String FullName = "";

        if (BadName != null)
        {
            String[] FullBadName = BadName.Split(' ');
            foreach (string Name in FullBadName)
            {
                String SmallName = "";
                if (Name.Length > 1)
                {
                    SmallName = char.ToUpper(Name[0]) + Name.Substring(1).ToLower();
                }
                else
                {
                    SmallName = Name.ToUpper();
                }
                FullName = FullName + " " + SmallName;
            }

        }
        FullName = FullName.Trim();
        FullName = FullName.TrimEnd();
        FullName = FullName.TrimStart();
        return FullName;
    }
Marius
  • 3,372
  • 1
  • 30
  • 36
0

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)));;
    }
DLL_Whisperer
  • 815
  • 9
  • 22
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
string Input = "    it is my text";

Input = Input.TrimStart();

//Create a char array
char[] Letters = Input.ToCharArray();

//Make first letter a capital one
string First = char.ToUpper(Letters[0]).ToString();

//Concatenate 
string Output = string.Concat(First,Input.Substring(1));
Marius
  • 3,372
  • 1
  • 30
  • 36
Mikhail
  • 1
  • 3
-1

Try this code snippet:

char nm[] = "this is a test";

if(char.IsLower(nm[0]))  nm[0] = char.ToUpper(nm[0]);

//print result: This is a test
Tomasz Dzięcielewski
  • 3,829
  • 4
  • 33
  • 47
Yair
  • 1