Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

White space "trim" 1

Status
Not open for further replies.

chispavip

IS-IT--Management
Dec 20, 2006
10
MX
It is an easy question and it's something that I can do easily.

Anyway, I'd like to know
Is there a function to remove white spaces on a string?
leaving just 1 space

Something like this
"Hello World!" -> "Hello World!"

Using the trim function removes the beginning and ending spaces, but Id like to remove all the white spaces excepting those that are between words leaving just 1
 
Using two regex's is one way. If you want to remove a leading space you can trim but I was thinking about indentation.
Code:
using System;
using System.Text.RegularExpressions;

class RegexTest
{
    static void Main(string[] args)
    {
        string myString = @" Hello      World   .";
        string spacesBetweenWords = @"\s{2,}";
        string spacesBetweenPunctuation = @"\s(\!|\.|\?|\;|\,|\:)";
        myString = Regex.Replace(myString, spacesBetweenWords, " ");
        myString = Regex.Replace(myString, spacesBetweenPunctuation, "$1");
        Console.WriteLine(myString);
    }
}
Marty

Funny, I can no longer do this in 2.0.
Regex myRegex = new Regex();
Inaccessible due to it's protection level. If I give the constructor a pattern it compiles fine.
 
you could also try this

Code:
Text = "Hello         World";
while(Text.IndexOf("  ") > -1)
{
	Text = Text.Replace("  "," ");
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top