MVC ASP.NET C# SQL Server WCF Written Test HR Round Subscribe C# Videos C# Programs Buy DVD

Insert space before every upper case letter in a string

Write a c# program that inserts a single space before every upper case letter. For example, if I have string like "ProductUnitPrice", the program should convert it to "Product Unit Price". Usually database column names will not have spaces, but when you display them to the user, it makes sense to have spaces.



using System;
using System.Text;


namespace SamplePrograms
{
    class SpaceBeforeUpperCaseLetter
    {
        public static void Main()
        {
            // Prompt the user for input
            Console.WriteLine("Please enter your string");
            
            // Read the input from the console
            string UserInput = Console.ReadLine();


            // Convert the input string into character array
            char[] arrUserInput = UserInput.ToCharArray();


            // Initialize a string builder object for the output
            StringBuilder sbOutPut = new StringBuilder();


            // Loop thru each character in the string array
            foreach (char character in arrUserInput)
            {
                // If the character is in uppercase
                if (char.IsUpper(character))
                {
                    // Append space
                    sbOutPut.Append(" ");
                }
                // Append every charcter to reform the output
                sbOutPut.Append(character);
            }
            // Remove the space at the begining of the string
            sbOutPut.Remove(0, 1);


            // Print the output
            Console.WriteLine(sbOutPut.ToString());


            Console.ReadLine();
        }
    }
}

2 comments: