Inserting Substrings in C# Using string.Insert(): String Manipulation
Learn how to use C#'s `string.Insert()` method to insert substrings into strings at specific positions. This tutorial explains its functionality, provides code examples, and emphasizes error handling to ensure efficient and safe string manipulation.
Inserting Substrings in C# Using `string.Insert()`
Introduction
The `string.Insert()` method in C# inserts a specified substring into a string at a particular index position. The original string remains unchanged; `Insert()` returns a *new* string with the inserted text.
`string.Insert()` Method Signature
`string.Insert()` Signature
public string Insert(int startIndex, string value);
Parameters
startIndex
: The zero-based index position where the insertion will occur. The first character is at index 0.value
: The string to be inserted.
Return Value
A new string with the value
inserted at the specified startIndex
.
Example: Inserting a Substring
Example: Inserting a Substring
using System;
public class StringExample {
public static void Main(string[] args) {
string originalString = "Hello C#";
string newString = originalString.Insert(5, "-");
Console.WriteLine(newString); // Output: Hello- C#
}
}
Example Output
Hello- C#
Explanation
The code inserts the string "-" at index position 5 in "Hello C#". The resulting string "Hello- C#" is stored in `newString`. The original string `originalString` remains unchanged.
Important Note: Index Out of Range
If `startIndex` is out of range (less than 0 or greater than the length of the string), an `ArgumentOutOfRangeException` is thrown. Always ensure that your index is valid before calling `Insert()`.
Conclusion
The `string.Insert()` method provides a straightforward way to modify strings by inserting substrings at specific positions. Remember that it returns a *new* string; the original string remains unchanged.