How to uppercase (capitalize) the first letter (character) of a string in C#

2 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    static class Program
    {
        static void Main(string[] args)
        {
            string s1 = "obi-wan kenobi";
            string s2 = "c# programming language";

            s1 = s1.UppercaseFirstCharacter();
            Console.WriteLine(s1);

            s2 = s2.UppercaseFirstCharacter();
            Console.WriteLine(s2);
        }
        // extension method
        public static string UppercaseFirstCharacter(this string s)
        {
            if (s.Length > 0)
            {
                char[] arr = s.ToCharArray();
                arr[0] = char.ToUpper(arr[0]);

                return new string(arr);
            }
            return s;
        }
    }
}


/*
run:

Obi-wan kenobi
C# programming language

*/

 



answered Jan 3, 2017 by avibootz
edited Jan 24, 2017 by avibootz
0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = "c# is a multi-paradigm programming language";
            string s2 = "star wars is an American epic space film series";

            s1 = FirstCharToUpper(s1);
            s2 = FirstCharToUpper(s2);

            Console.WriteLine(s1);
            Console.WriteLine(s2);
        }
        public static string FirstCharToUpper(string s)
        {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentException("String Is Null Or Empty");

            return s.First().ToString().ToUpper() + s.Substring(1);
        }
    }
}

/*
run:

C# is a multi-paradigm programming language
Star wars is an American epic space film series

*/

 



answered Jan 24, 2017 by avibootz
...