0

I cannot, for the life of me, understand why the Replace(); method will not work when I try to replace the text of an element inside a list of type String. This question is, to an extent, related to a previous thread of mine [found here: Merging two files and handling duplicate entries (would be a good idea to view it, as well, for the full code)], but at the end of the day, it all boils down to the fact that the command doesn't work while, my code, is actually correct (!).

I'll give you an example of what doesn't work in my situation. In its most basic form, for the sake of example, this is what I'm trying to accomplish but it doesn't work (for real!):

[In my original code, I've triple-checked (with breakpoints and everything) that my list indeed contains the string I want to replace (I'm replacing the element itself!), but it just won't do it! Seriously now, it is a 4 element list at the present time (although more elements CAN be added, refer to other thread).]

One last thing, sorry about the punctuation (too many exclamation marks, I know), but I'm actually raging over this. Code below (remember, most basic form, but an example I tried):

// List[index].Replace(oldValue, newValue);
newFile[3].Replace(newFile[3], "Replace it with this!");

Could you help me with this?

4

2 回答 2

10
newFile[3] = newFile[3].Replace(newFile[3], "Replace it with this!");

In c#, strings are immutable. As such, the Replace method returns a new string.

Edit: The main reason for strings to be immutable is to make them thread-safe. If you wanna find out more, have a read: Why .NET String is immutable?

于 2013-09-10T17:13:56.980 回答
2
newFile[3] = newFile[3].Replace(newFile[3], "Replace it with this!");
于 2013-09-10T17:14:34.913 回答