6

i have a String Array which comes from a splitted String

string[] newName= oldName.Split('\\');

newName.Last().Replace(newName.Last(), handover);

Why doesnt this replaces my last element in the Array?

last() comes from using linq

regards

2 Answers 2

14

Calling string.Replace doesn't alter the existing string - strings are immutable.

Instead, it returns a new string, with the appropriate replacements. However, you're not using the return value, so it's basically a no-op.

You need to change the array element itself to refer to a different string. Something like this:

newName[newName.Length - 1] = handover;
1
  • Thx that worked fine. Never mentioned that its adding a new string there. Should have to read the manual;) replace ... Commented Sep 3, 2010 at 9:12
9

Also, starting with .NET Core 3.0 (and .NET Standard 2.1) you can use Index type to get/set array elements (like strings) from the end.
See example below:

newName[^1] = handover;

See docs for additional info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.