Capitalize each word in a string

The CapitalizeString method uses regular expressions to capitalize every word in a string.
//using System.Text.RegularExpressions;
 
static string CapitalizeString(Match matchString)
{
    string strTemp = matchString.ToString();
    strTemp = char.ToUpper(strTemp[0]) + strTemp.Substring(1, strTemp.Length - 1).ToLower();
    return strTemp;
}
 
// How to use the method
private void Form1_Load(object sender, EventArgs e)
{
    // This will be transformed into 'The World Is Full Of Complainers...' and so on
    string StringToCap = "The world is full of complainers. And the fact is, nothing comes with a guarantee. Now I don't care if you're the pope of Rome, President of the United States or Man of the Year; something can all go wrong. Now go on ahead, you know, complain, tell your problems to your neighbor, ask for help, and watch him fly. Now, in Russia, they got it mapped out so that everyone pulls for everyone else... that's the theory, anyway. But what I know about is Texas, and down here... you're on your own.";
    string ResultingString = Regex.Replace(StringToCap, @"\w+", new MatchEvaluator(CapitalizeString));
    MessageBox.Show(ResultingString);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top