0

i have a vb.net project and i have text in a multi-line textbox like this

  abc
  def
   ghi
        jkl
 mn

every line starts with spaces i want to remove the initial spaces from all line

i've tried

For Each lne In TextBox1.Lines
            If lne.StartsWith(" ") Then
                TextBox1.Text = TextBox1.Text.Replace(" ", "")
            End If
        Next

but it deletes other texts in the text box and won't work

Ahmed Mohsen
  • 1
  • 1
  • 6
  • You need to use a regular expression somehow. In POSIX regex notation, you want to replace `^[[:space:]]*` with the empty string. I don't know how to do that in vb.net. – András Korn Jan 22 '16 at 20:19
  • 2
    RegEx? For this? Overkill, overkill, overkill. – Tim Jan 22 '16 at 20:29
  • 3
    Overkill^Overkill, infact. – Fᴀʀʜᴀɴ Aɴᴀᴍ Jan 22 '16 at 20:29
  • I agree with the general usage of `TrimStart`, but it is important to note that your code is basically saying "As soon as I find a line with a leading space, delete ALL spaces in my textbox". That is why it will be modifying more than you want. – Nathan C Jan 22 '16 at 20:39

1 Answers1

5

You can use this:

Dim result As String = ""
For Each lne In TextBox1.Lines
   result += lne.TrimStart() & Environment.NewLine
Next
TextBox1.Text = result

The above method uses the String.TrimStart() function to remove the leading whitespaces from each line.

Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
  • Note that TextBox1's Text field is only overwritten at the end. That is an important difference to the original problem code. The only thing I would change is using a `StringBuilder` instead of String Concatenation – Nathan C Jan 22 '16 at 20:41