String.Substring Method (int startIndex, int length)
Syntax
public string Substring(int startIndex, int length);
Parameters
- startIndex: The zero-based starting character position of a substring in this instance
- length: The number of characters in the substring.
Return Value
This method returns a string that starts at startIndex and has a specified number of characters length.
Exceptions:
ArgumentOutOfRangeException: Thrown if startIndex or startIndex + length is out of range.
Example
C#
string example = "Hello, world!";
string substring = example.Substring(0, 5);
Console.WriteLine(substring);
Output:
"Hello"
In this example, the Substring method extracts the first five characters from the string. It starts at index 0 and continues to index 4, which makes up the substring "Hello". This function is highly useful for tasks such as extracting specific parts of strings based on known indices and lengths.
Frequently Asked Questions
What happens if startIndex is equal to the string's length?
If startIndex equals the string's length, the Substring method returns an empty string. This is because the starting position does not precede any characters within the string.
Can Substring be used with arrays or only strings?
The Substring method is specifically designed for use with strings. To extract elements from an array, you would use different methods, such as array slicing or LINQ queries in C#.
Is it possible to modify the string returned by Substring?
Strings in C# are immutable, which means the string returned by Substring cannot be modified directly. However, you can manipulate the returned string by creating a new string based on operations performed on the substring.
Conclusion
In this article, we learned about the Substring method in C#, which allows us to extract a portion of a string. We discussed two overloads of the method: one that takes only the starting index and another that takes both the starting index and the length of the substring. We also looked at examples to understand how to use the Substring method effectively.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.