C# Substring Operations

The Substring() method in C# is used to extract parts of a string. You can provide a starting index and an optional length to retrieve a substring.

Key Topics

1. Basic Usage

Example: Extracting Substring from Index

string message = "Hello, World!";
string subMessage = message.Substring(7);
Console.WriteLine(subMessage);  // Outputs: World!

Output:

World!

2. Substring with Length

Example: Extracting Substring with Start Index and Length

string message = "Hello, World!";
string subMessage = message.Substring(7, 5);
Console.WriteLine(subMessage);  // Outputs: World

Output:

World

3. Handling Edge Cases

Using invalid indices can cause exceptions.

Example: Avoiding Exceptions

string message = "Hello";
// This will throw an ArgumentOutOfRangeException
string subMessage = message.Substring(10);

Explanation: The starting index exceeds the length of the string, resulting in an exception. Always ensure indices are within the valid range.

Key Takeaways

  • The Substring() method extracts parts of a string starting from a specified index.
  • You can optionally specify the length of the substring to extract.
  • Ensure that the starting index and length are within the bounds of the string to prevent exceptions.