开发者

C# String Array Replace Last Element

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


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;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜