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
Tweet
No comments:
Post a Comment