Replacing multiple identical characters with one in a string

I have a line like this:

dim str as string = "this       is    a string      .   "

      

I want to identify those multiple spaces and replace with one char space. using the replace function will replace all of them, so what is the correct way to accomplish such a task?

0


a source to share


4 answers


import System.Text.RegularExpressions            

dim str as string  = "This is a      test   ."
dim r as RegEx = new Regex("[ ]+")
str = r.Replace(str, " ")

      



+2


a source


Use the Regex class to match the "one or more spaces" pattern, and then replace all of those instances with one space.

Here is the C # code:



Regex regex = new Regex(" +");
string oldString = "this       is    a string      .   ";
string newString = regex.Replace(oldString, " ");

      

+2


a source


I would use the \ s + modifier which is easier to read

public Regex MyRegex = new Regex(
      "\\s+",
    RegexOptions.Multiline
    | RegexOptions.CultureInvariant
    | RegexOptions.Compiled
    );


// This is the replacement string
public string MyRegexReplace =   " ";

string result = MyRegex.Replace(InputText,MyRegexReplace);

      

Or in VB

Public Dim MyRegex As Regex = New Regex( _
      "\s+", _
    RegexOptions.Multiline _
    Or RegexOptions.CultureInvariant _
    Or RegexOptions.Compiled _
    )


Public Dim MyRegexReplace As String =  " "


Dim result As String = MyRegex.Replace(InputText,MyRegexReplace)

      

+1


a source


Use a regular expression. as suggested by this other SO userhere

0


a source







All Articles