RSS

Split words by capital letter using Regex

20 Jan

Say we want to split the words HoleWizard, ManyToMany into such strings as “Hole Wizard”, or “Many To Many”. Using Regex is a good choice. I don’t know if the following code is the best or not, but it just works.

string BreakWordBySmallBigLetter(string inputstr)
{
Regex reg = new Regex(@”([a-z])[A-Z]”);
MatchCollection col= reg.Matches(inputstr);
int iStart = 0;
string Final = string.Empty;
foreach (Match m in col)
{
int i = m.Index;

Final +=inputstr.Substring(iStart, i-iStart+1)+ ” “;
iStart = i+1;
}
string Last = inputstr.Substring(iStart, inputstr.Length – iStart);
Final += Last;
return Final;
}

Calling Example:
string outputstr = BreakWordBySmallBigLetter(inputstr);

 
1 Comment

Posted by on January 20, 2009 in Dotnet/C#

 

One response to “Split words by capital letter using Regex

  1. Alex Walsh

    June 16, 2009 at 2:58 am

    Love it! Thanks so much. I was too lazy to do it myself! 🙂

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: