Iterates thru an entire string, and sets the first letter of each word to uppercase, and all ensuing letters to lowercase - CSharp System

CSharp examples for System:String Case

Description

Iterates thru an entire string, and sets the first letter of each word to uppercase, and all ensuing letters to lowercase

Demo Code


using System.Web;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;// w  w  w  .  j av  a 2s  . co  m

public class Main{
        #endregion

        #region StringEdits
        /// <summary>
        /// Iterates thru an entire string, and sets the first letter of
        /// each word to uppercase, and all ensuing letters to lowercase
        /// </summary>
        /// <param name="stream">The string to alter the case of</param>
        /// <returns>
        /// Same string w/uppercase initial letters & others as lowercase
        /// </returns>
        public static string MixCase(string stream)
        {
            try
            {
                string newString = string.Empty;
                string character = string.Empty;
                string preceder = string.Empty;
                for (int i = 0; i < stream.Length; i++)
                {
                    character = stream.Substring(i, 1);
                    if (i > 0)
                    {
                        //look at the character immediately before current
                        preceder = stream.Substring(i - 1, 1);
                        //remove white space character from predecessor
                        if (preceder.Trim() == string.Empty)
                            //the preceding character WAS white space, so
                            //we'll change the current character to UPPER
                            character = character.ToUpper();
                        else
                            //the preceding character was NOT white space,
                            //we'll force the current character to LOWER
                            character = character.ToLower();
                    }
                    else
                        //index is 0, thus we are at the first character
                        character = character.ToUpper();
                    //add the altered character to the new string:
                    newString += character;
                }
                return newString;
            }
            catch (Exception ex)
            {
                //ErrorTool.ProcessError(ex);
                return null;
            }
        }
}

Related Tutorials