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);
}
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top