Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Replace in VB.NET

Tags:

vb.net

I am making a program i.e. a script converter. I tried the Replace Command TextBox1.Text.Replace("Hi", "Hello").Replace("Hello", "HI") But this doesn't work. It doesn't replace the second time correctly.

Please Help...

like image 344
shahbaz Avatar asked May 16 '12 03:05

shahbaz


2 Answers

The Replace() method doesn't actually change the contents of a String. So you have to assign the new value to something.

An example:

someString = "First Example"

someString.Replace("First", "Second")

// someString is still "First Example"

newString = "Hello World".Replace("Hello", "Hi")

// newString is now "Hi World"

Some examples: http://www.dotnetperls.com/replace-vbnet

Update:

From your recent comment, it seems what you want it this:

TextBox1.Text.Replace("Hi", "temp").Replace("Hello", "HI").Replace("temp", "Hello")

Because the second replace is working on the result of the first replace. It's not working on the original text any more. So to switch 'hi' with 'hello' and 'hello' with 'hi' you have to have some intermediate value.

like image 189
David Avatar answered Oct 29 '22 17:10

David


Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
    TextBox1.Text = TextBox1.Text.Replace("Hi", "Hello").Replace("Hello", "HI")
End Sub

I guess this what you want, works for me

like image 38
Darshana Avatar answered Oct 29 '22 17:10

Darshana