'string.insert in c# doesn't overwrite does it?
string.insert in c# doesn't overwrite the character that is in the startindex does it?
Solution 1:[1]
Insert does addition only. Replace does change.
Edit: As others pointed out, strings are actual immutable, so both methods will return copy of your initial string. However, the semantic of the operations is as above.
Solution 2:[2]
No. Strings are immutable. string.Insert returns a new string with the inserted value. It does not change the old string.
string newString = oldString.Insert(3, "foo");
oldString does not change. But "foo" is now in newString.
Solution 3:[3]
Strings in c# are immutable. They cannot be changed except by reflection or unsafe code (and you should never do this).
All methods on string which 'modify' it instead return a new string with the appropriate modifications.
Since insert is placing one string within another the result of an insert of string s1 into string s2 will be a string of length s1.Lnegth + s2.Length, no characters are lost.
Solution 4:[4]
No. It just tells it where to insert the character, so if you had the following
string x = "ello".Insert(0, "h");
the string would actually read "hello".
Solution 5:[5]
No, definitely not.
But the best practice is to use StringBuilder instead of immutable strings if you're doing changes to the string in-flight.
Here's a nice overview.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Johwhite |
| Solution 3 | ShuggyCoUk |
| Solution 4 | Pete OHanlon |
| Solution 5 | Rap |
