What's the cleanest way of editing the characters in a string in C#?
What's the C# equivalent of this in C++:
std::string myString = "boom";
myString[0] = "d";
No, you cannot modify it, as the string can be stored in read-only memory. If you want to modify it, you can use an array instead e.g. char a[] = "This is a string"; Or alternately, you could allocate memory using malloc e.g.
Hence, strings are ordered collections of characters that are immutable in nature. This means that you cannot add, update or delete the string after it is created. If any operations are to be performed, a copy of an original string is created and updated accordingly.
To change a specific character in a string to another value, we refer to the index number position of the character in the string and use single quotation marks ( ' ' ). To access a character of a string in C++, we simply specify the index position of the character in the string in square brackets [] .
According to java, you are only not allowed to change the string object, but you can still modify that object. There are several ways by which you can create a string object and hence declare a string. But for now, we take the simplest way to declare the string, which is as follows; String S= “Hello”;.
Use a StringBuilder
instead.
string is immutable as described by MSDN:
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.
So you want something like:
StringBuilder sb = new StringBuilder("Bello World!");
sb[0] = 'H';
string str = sb.ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With