Search This Blog

Saturday, October 15, 2016

Convert first letter of string to uppercase

Convert first letter of string to uppercase:

In many of the programming situations, we need to convert first letter of string to uppercase.

Here we can have two conditions for converting string first letter uppercase
Case 1. Convert only first letter of string to uppercase. (this is an example - This is an example)
Case 2. Convert first letter of each word in string to uppercase Camel Case.(this is an example - This Is An Example)  

Here I'll explain how can we achieve this in an optimum way. 

For case 1 the optimum solution algorithm is
Step 1. Find the string.
Step 2. Find first letter of string
Step 3. Convert to uppercase.
Step 4. Append rest string to first letter
Step 5. Return string.

For case 2 the optimum algorithm is
Step 1. Find the string
Step 2. Split string from space position and get array of words of string
Step 3. Call case 1 for each element of array and append space and words
Step 5. return string.

Code segment for case 1

        public string ToUpperFirstCharacter(string str)
            return str.First().ToString().ToUpper() + str.Substring(1, str.Length-1);

Code segment for case 2

        public string ToCamelCase(string str)
            string[] substr = str.Split(' ');
            string convertedString ="";
            for (int i = 0; i < substr.Length; i++)
                string word = substr[i];
                convertedString = convertedString + " " + word.First().ToString().ToUpper() +                                                                   word.Substring(1, word.Length - 1);
            return convertedString;

Alternate approach for case 2
        public static string ToCamelCase(this string str)
            return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.

Complete code console application

Complete code console application


No comments:

Post a Comment