I have a training program that is used by MANY different people. I have encountered many formatting issues already (like not allowing initials) but now I have a new one that I'm not sure about. When the code tests the name in the TextBox.Leave function, I can find if there is more than one space character in the box, and I can see if it is between the names, but if there is more than one, how do I remove ONLY one space?

5 Years
Discussion Span
Last Post by bklynman01

To remove ALL spaces:

myString = myString.Replace(" ", "")

To remove leading and trailing spaces:

myString = myString.Trim()

Note: this removes any white space, so newlines, tabs, etc. would be removed.


I am able to remove leading, trailing, and all spaces, but that's not what I want to do. Example: (where the "_" is a space) the user enters "John__Doe". I want the program to save "John_Doe". How can I do this?

Edited by bklynman01: clarification in example

Dim StringWithMultipleSpaces As String = " John  Doe"
Dim StringWithOneSpace As String = String.Join(" ", StringWithMultipleSpaces.Trim.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))

Edited by Unhnd_Exception: n/a


This should work....

Dim target As String
        target = "  "
        Dim replacement As String
        replacement = " "
        Dim sentence As String
        sentence = "John<space><space>Doe."
        TextBox2.Text = sentence
        Dim update As String
        update = sentence.Trim().Replace(target, replacement)
        TextBox1.Text = update

@Unhnd Exception: I'm sorry, but I do not understand your code. I have placed it in the textbox.leave function, but it does nothing, regardless of text format.

@visharlrane: you had the right idea. But that code only works if there are two spaces next to each other. I must be able to account for all types of situations, i.e.: "<space>John<space><space><space>Doe<space>" should be "John<space>Doe".

I am yet to get this task completed. If anyone has any ideas, I'm willing to try them!

TextBox1.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))

If you had this "<4 spaces> John <10 spaces> Doe <1000 spaces>"

The TextBox1.Text.Split(New Char() {" "}c, StringSplitOptions.RemoveEmptyEntries part will return a string array containing 2 items John,Doe. The String.Join part puts them back together with 1 space inbetween. Resulting in "John Doe".

Edited by Unhnd_Exception: n/a


Unhnd Exception: EXCELLENT!!

I understand now how that works. And I did realize after my last post that I did not have the textbox.text set to refresh with the command.

This works perfectly. Thank you very much!!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.