Sunday, August 24, 2008

C#: Handling Strings

Often, in the real time application development, we come across Strings that need to be handled differently based on the need.

String reverse:
One such function is the String reverse. To accomplish this in C#, we need to add reference to the Microsoft.VisualBasic assembly and you can write the code to reverse the string as follows -

String str = "Welcome";
str = Microsoft.VisualBasic.Strings.StrReverse(str);
Response.Write(str);

Word Count:
String str = "Welcome to ASP.NET with C#.";
System.Text.RegularExpressions.MatchCollection wordCountColl
= System.Text.RegularExpressions.Regex.Matches(str, @"[\S]+");
Response.Write(wordCountColl.Count.ToString());

Character Count:
String str = "Welcome to ASP.NET with C#. Welcome to ASP.NET with C#.";
System.Text.RegularExpressions.MatchCollection charCountColl
= System.Text.RegularExpressions.Regex.Matches(str, @".");
Response.Write(charCountColl.Count.ToString());

No comments: