Is there a convenient way to get part of a string from one index to another in C#?

Viewed 142

Is there a way to retrieve the part of a string between two indexes in C#? For example given this string,

Hello, world!

is there a convenient method to which I can pass "7" and "11" (the indexes of "w" and "d") and get "world"?

Note that I am aware of the String.Substring() method, and I know that I can do the following:

string s = "Hello, world!";
s.Substring(7, 11 - 7 + 1); // => "world"

I also realize that it would be trivial to create an extension method such as the following:

public static class Extensions {
    public static string SubstringByIndexes(this string str, int start, int end) {
        return str.Substring(start, end - start + 1);
    }
}

However, I just wanted to make sure that there is no built-in way before I start lugging this method around in whatever projects I am working on.

1 Answers

You can use ranges, these were added in C# 8. Note the latter index is 12, not 11, in order to produce "world".

string s = "Hello, world!";
string world = s[7..12];
Related