Criel
Criel

Reputation: 815

Why isn't my String updating?

I have a small string variable with a length of 400-500 characters spaces included. I've tried a few things as far as removing some parts of the string, while in a Do/While loop. I'm looking to go through the loop, then remove 300 characters from it, however it doesn't seem to be actually removing it from the string.

Are we not actually able to modify a string object and must be forced to SubString the text variable to get the desired result?

Do while stringText.Length >= 300
'stringText.replace(textToRemove, "") This doesn't replace the string variable
'stringText.Remove(0,299) This also doesn't remove the specified range of characters
Loop

Upvotes: 0

Views: 145

Answers (3)

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

Strings in .NET and VB are immutable, meaning that a string can never change once it's been defined. What the various Replace/Remove methods do is return a new, modified string, which you can store to the same variable.

Like this:

Do while stringText.Length >= 300
   stringText = stringText.Replace(textToRemove, "") 
Loop

It's important to note, though, that this is potentially expensive - a new string object is allocated. If you have a lot of modifications to make to a string separately, each one will create a new copy, and for large strings it might create unnecessary memory allocations.

For this reason, we have the System.Text.StringBuilder class (as mentioned by roryap), which lets us manipulate strings directly. Read up on it.

Upvotes: 4

Nagaraj S
Nagaraj S

Reputation: 13484

You have to assign string for the return value

stringText =stringText.replace(textToRemove, "") 

Upvotes: 2

Charleh
Charleh

Reputation: 14002

These functions return a value, you must assign the value returned to the original string for it to be updated:

e.g.

stringText = stringText.replace(textToRemove, "")

Otherwise you are just discarding the value returned - the functions do not mutate the original string

Upvotes: 2

Related Questions