Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to change a character from a string
In C#, strings are immutable, meaning their characters cannot be changed directly. However, you can change characters in a string using the StringBuilder class, which provides a mutable sequence of characters.
The StringBuilder class allows you to modify individual characters using indexer notation str[index] = newChar, where the index is zero-based.
Syntax
Following is the syntax for changing a character in a StringBuilder −
StringBuilder stringBuilder = new StringBuilder("original");
stringBuilder[index] = 'newChar';
Using StringBuilder to Change Characters
Let's say our string is −
StringBuilder str = new StringBuilder();
str.Append("pre");
To change a character, set the value at that particular index. The following sets a character at the 3rd position (index 2) −
str[2] = 'o';
Example
using System;
using System.Text;
public class Demo {
public static void Main() {
StringBuilder str = new StringBuilder();
str.Append("pre");
Console.WriteLine("String : " + str);
Console.WriteLine("Change 3rd character");
str[2] = 'o';
Console.WriteLine("New String : " + str);
}
}
The output of the above code is −
String : pre Change 3rd character New String : pro
Changing Multiple Characters
Example
using System;
using System.Text;
public class Demo {
public static void Main() {
StringBuilder str = new StringBuilder("hello");
Console.WriteLine("Original String: " + str);
str[0] = 'H'; // Change first character
str[4] = 'a'; // Change last character
Console.WriteLine("Modified String: " + str);
}
}
The output of the above code is −
Original String: hello Modified String: Hella
Alternative Method using String Methods
For immutable strings, you can create a new string with changed characters using string manipulation methods −
Example
using System;
public class Demo {
public static void Main() {
string originalString = "hello";
Console.WriteLine("Original String: " + originalString);
// Change character at index 1 from 'e' to 'a'
string newString = originalString.Substring(0, 1) + 'a' + originalString.Substring(2);
Console.WriteLine("Modified String: " + newString);
}
}
The output of the above code is −
Original String: hello Modified String: hallo
Comparison of Methods
| Method | Mutability | Performance | Use Case |
|---|---|---|---|
| StringBuilder | Mutable | Better for multiple changes | Frequent character modifications |
| String methods | Immutable | Creates new string objects | Single character change |
Conclusion
Use StringBuilder for efficient character modification when you need to change multiple characters. For single character changes, string manipulation methods work well, but remember they create new string objects rather than modifying the original.
