Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I set a character at an index in a string in c#?

Tags:

c#

someString[someRandomIdx] = 'g'; 

will give me an error.

How do I achieve the above?

like image 774
matt Avatar asked Jul 22 '10 07:07

matt


People also ask

How do you index a character in a string?

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string: String anotherPalindrome = "Niagara.

Can you index a char in c?

The index() function locates the first occurrence of c (converted to an unsigned char) in the string pointed to by string. The character c can be the NULL character (\0); the ending NULL is included in the search. The string argument to the function must contain a NULL character (\0) marking the end of the string.

How do you get a certain index of a string in c?

Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string);

How do I replace a character in a string in C#?

In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it.


2 Answers

If it is of type string then you can't do that because strings are immutable - they cannot be changed once they are set.

To achieve what you desire, you can use a StringBuilder

StringBuilder someString = new StringBuilder("someString");  someString[4] = 'g'; 

Update

Why use a string, instead of a StringBuilder? For lots of reasons. Here are some I can think of:

  • Accessing the value of a string is faster.
  • strings can be interned (this doesn't always happen), so that if you create a string with the same value then no extra memory is used.
  • strings are immutable, so they work better in hash based collections and they are inherently thread safe.
like image 114
Matt Ellen Avatar answered Sep 22 '22 22:09

Matt Ellen


C# strings are immutable. You should create a new string with the modified contents.

 char[] charArr = someString.ToCharArray();  charArr[someRandomIdx] = 'g'; // freely modify the array  someString = new string(charArr); // create a new string with array contents. 
like image 27
mmx Avatar answered Sep 22 '22 22:09

mmx