[RESOLVED] [2005] Simple Question
What's the best method to turn multiple spaces in a string into one?
So for instance I have something like
"Word1 Space(5) Word2 Space(6) Word3"
I want to make it so that there is only one space between the words:
"Word1 Word2 Word3"
Best way? I've been doing .Net for a while and I just had a mind blank when I came across this.
Thanks!
Re: [2005] Simple Question
You'd use Regex.Replace. My knowledge of regular expression syntax is fairly rudimentary though, so I don't know what the pattern for two or more spaces is. It would be quite simple though, so you can try to research it for yourself or just wait for someone else to provide it for you.
Re: [2005] Simple Question
The post link was not right.
The title of the post was
[2005] String.Trim help
the answer was supplied by Wild Bill
Re: [2005] Simple Question
Quote:
Originally Posted by rjdpa
What's the best method to turn multiple spaces in a string into one?
So for instance I have something like
"Word1 Space(5) Word2 Space(6) Word3"
I want to make it so that there is only one space between the words:
"Word1 Word2 Word3"
Best way? I've been doing .Net for a while and I just had a mind blank when I came across this.
Thanks!
Hi,
You can try this:
Code:
(Word1) & Space(1) & (Word2) & Space(1) & (Word3))
Here's a small test, 3 textboxes and a button and in the button event this code:
Code:
MsgBox((TextBox1.Text) & Space(1) & (TextBox2.Text) & Space(1) & (TextBox3.Text))
Hope it helps you,
sparrow1
Re: [2005] Simple Question
I'll go with JMC suggestion. Try something like this:
Code:
Dim originalString As String = "This is some text with various spacings between words"
Dim modifiedString As String = System.Text.RegularExpressions.Regex.Replace(originalString, "\s{2,}", " ")
MessageBox.Show(modifiedString)
Re: [2005] Simple Question
Quote:
Originally Posted by CoachBarker
The post link was not right.
The title of the post was
[2005] String.Trim help
the answer was supplied by Wild Bill
that only works for trimming leading and trailing spaces.... doesn't remove multiple spaces between words..
sparrow - um..... I think you missed the point.... the string is already assembled and it has multiple spaces between the words....
stanav probably has the ideal solution....
-tg
Re: [2005] Simple Question
This is an alternative if you want to avoid RegEx:
Code:
Dim str As String = "feai ew f we fe ewf j iewf"
While str.IndexOf(Space(2)) > 0
str = str.Replace(Space(2), Space(1))
End While
Re: [2005] Simple Question
Quote:
Originally Posted by trisuglow
This is an alternative if you want to avoid RegEx:
Code:
Dim str As String = "feai ew f we fe ewf j iewf"
While str.IndexOf(Space(2)) > 0
str = str.Replace(Space(2), Space(1))
End While
This worked perfect! thank you!