有没有一种方便的方法可以在 C# 中从一个索引到另一个索引获取字符串的一部分?

Jac*_*ard 2 c#

有没有办法在 C# 中检索两个索引之间的字符串部分?例如给定这个字符串,

Hello, world!
Run Code Online (Sandbox Code Playgroud)

有没有一种方便的方法可以传递“7”和“11”(“w”和“d”的索引)并获得“world”?

请注意,我知道该String.Substring()方法,并且我知道我可以执行以下操作:

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

我也意识到创建一个扩展方法是微不足道的,例如:

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

但是,在我开始在我正在从事的任何项目中使用这种方法之前,我只是想确保没有内置方法。

Ben*_*Ben 5

您可以使用range,这些是在 C# 8 中添加的。请注意,后一个索引是 12,而不是 11,以便生成“world”。

string s = "Hello, world!";
string world = s[7..12];
Run Code Online (Sandbox Code Playgroud)