September 28, 2009

Handle Uneven Spaces in a String using C# or VB.NET




I was facing a requirement where the words in a string that was sent to an application had uneven spaces in it. The client wanted the string spacing to be readjusted to allow just one space between two words. Here’s how I solved it using Regex:


Add a reference to System.Text.RegularExpressions


C#

string str = "This string   has    odd number of spaces";

Console.WriteLine("Before adjusting spaces : " + str);

string newStr = Regex.Replace(str, @"\s+", " ");

Console.WriteLine("After adjusting spaces : " + newStr);

Console.ReadLine();

VB.NET

Dim str As String = "This string   has    odd number of spaces"

Console.WriteLine("Before adjusting spaces : " & str)

Dim newStr As String = Regex.Replace(str, "\s+", " ")

Console.WriteLine("After adjusting spaces : " & newStr)

Console.ReadLine()

OUTPUT


image



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Handle Uneven Spaces in a String using C# or VB.NET"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions