someString[someRandomIdx] = 'g';
will give me an error.
How do I achieve the above?
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.
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.
Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string);
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.
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:
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.
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