Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit characters in a String in C#

Tags:

c++

string

c#

.net

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";
like image 212
Robben_Ford_Fan_boy Avatar asked May 28 '10 17:05

Robben_Ford_Fan_boy


People also ask

Can I modify a string in C?

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.

Can you change characters in a string?

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.

How do you change a letter in a string C?

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 [] .

Can we edit string?

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”;.


1 Answers

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();
like image 154
Brian R. Bondy Avatar answered Sep 21 '22 06:09

Brian R. Bondy