0

I need to remove extra adjacent "spaces" other than 1 "space" if the text of the rich textbox contains any.But the code doesn't seem to work.

Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
    For i As Integer = 0 To RichTextBox1.Text.Length - 2
        If RichTextBox1.Text.Chars(i) = " " And RichTextBox1.Text.Chars(i + 1) = " " Then
            RichTextBox1.Text.Replace(RichTextBox1.Text.Chars(i + 1, "")
        End If
    Next

End Sub
Pretty_Girl
  • 157
  • 1
  • 8

1 Answers1

0
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) _
    Handles RichTextBox1.TextChanged
    RichTextBox1.Text = Regex.Replace(RichTextBox1.Text.Trim ,"\s+", " ")
End Sub

Test:

Console.WriteLine(Regex.Replace("The brown        fox  jumped over the  lazy dog      ", "\s+", " "))

Output:

The brown fox jumped over the lazy dog
MrGadget
  • 1,258
  • 1
  • 10
  • 19
  • You'll need `Imports System.Text.RegularExpressions` for that. – MrGadget Feb 25 '16 at 04:44
  • The issue is I don't exactly how many "spaces" will lead after the first "space". I need to remove any excess spaces after the first space ... for instance: "The brown fox jumped over the" ---> "The brown fox jumped over the". – Pretty_Girl Feb 25 '16 at 06:18