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 remove characters starting at a particular index in StringBuilder
The StringBuilder class in C# provides the Remove() method to delete a sequence of characters starting from a specific index position. This method is more efficient than string manipulation when performing multiple character operations.
Syntax
Following is the syntax for the Remove() method −
StringBuilder.Remove(int startIndex, int length)
Parameters
-
startIndex − The zero-based position where removal begins.
-
length − The number of characters to remove.
Return Value
The method returns a reference to the same StringBuilder instance after the removal operation, allowing for method chaining.
Example
using System;
using System.Text;
public class Program {
public static void Main() {
StringBuilder str = new StringBuilder("Airport");
Console.WriteLine("Original String: " + str);
// removing four characters starting from index 3
str.Remove(3, 4);
Console.WriteLine("String after removing characters: " + str);
}
}
The output of the above code is −
Original String: Airport String after removing characters: Air
Using Remove() with Different Scenarios
Example
using System;
using System.Text;
public class Program {
public static void Main() {
StringBuilder sb = new StringBuilder("Programming");
Console.WriteLine("Original: " + sb);
// Remove single character at index 4
sb.Remove(4, 1);
Console.WriteLine("After removing 1 char at index 4: " + sb);
// Reset StringBuilder
sb = new StringBuilder("Programming");
// Remove from index 7 to end
sb.Remove(7, sb.Length - 7);
Console.WriteLine("After removing from index 7 to end: " + sb);
// Method chaining example
StringBuilder sb2 = new StringBuilder("Hello World!");
sb2.Remove(5, 6).Append(" C#");
Console.WriteLine("Method chaining result: " + sb2);
}
}
The output of the above code is −
Original: Programming After removing 1 char at index 4: Proramming After removing from index 7 to end: Program Method chaining result: Hello C#
Common Use Cases
-
Text Processing − Removing unwanted characters or substrings from dynamic text.
-
Data Cleanup − Removing specific portions of strings during data manipulation.
-
String Building − Correcting mistakes while building strings programmatically.
Conclusion
The StringBuilder.Remove() method efficiently removes characters from a specific index position. It modifies the existing StringBuilder instance and returns a reference to itself, making it ideal for chaining operations and avoiding the overhead of creating new string objects.
