String.Replace question

  • Thread starter Thread starter Craig Buchanan
  • Start date Start date
C

Craig Buchanan

If I have a string variable, is there a way to get the Replace method to
work on *its* contents, without having to dimenstion a second variable?
Something like:

Dim MyTest as String = "<hello/>"
MyTest.Replace("<", "&lt;")
MyTest.Replace(">", "&gt;")

'MyTest now equals "&lt;hello&gt;"

This code doesn't work the way that I would expect. Can someone shed some
light on this?

Thanks,

Craig
 
Craig Buchanan said:
If I have a string variable, is there a way to get the Replace method
to work on *its* contents, without having to dimenstion a second
variable? Something like:

Dim MyTest as String = "<hello/>"
MyTest.Replace("<", "&lt;")
MyTest.Replace(">", "&gt;")

'MyTest now equals "&lt;hello&gt;"

This code doesn't work the way that I would expect. Can someone shed
some light on this?

Replace is a function. It returns a *new* string because the string content
can *not* be changed.

mytest = MyTest.Replace("<", "&lt;")


--
Armin

How to quote and why:
http://www.plig.net/nnq/nquote.html
http://www.netmeister.org/news/learn2quote.html
 
Craig Buchanan said:
If I have a string variable, is there a way to get the Replace method to
work on *its* contents, without having to dimenstion a second variable?
Something like:

Dim MyTest as String = "<hello/>"
MyTest.Replace("<", "&lt;")
MyTest.Replace(">", "&gt;")

'MyTest now equals "&lt;hello&gt;"

This code doesn't work the way that I would expect. Can someone shed some
light on this?

Thanks,

Craig
If you need to modify existing contents, you need to use the
System.Text.StringBuilder class instead of the String class. StringBuilder
objects are mutable. String objects are immutable.
 
Hi Peter,
If you need to modify existing contents, you need to use the
System.Text.StringBuilder class instead of the String class. StringBuilder
objects are mutable. String objects are immutable.

To my suprise as well has that no effect on the replace, the string replace
is slighly faster, we did a test in this newsgroup, here the final link to
that thread.

http://tinyurl.com/3bogd

Cor
 
Cor Ligthert said:
Hi Peter,


To my suprise as well has that no effect on the replace, the string replace
is slighly faster, we did a test in this newsgroup, here the final link to
that thread.

http://tinyurl.com/3bogd

Cor
I was referring to the general issue of mutability. Not in particular to the
Replace method, or to any performance concerns. The parameter lists for the
Replace methods for the two classes explains the behavior.
 
Back
Top