使用已知的Start&Endindex剪切字符串

Jan*_*n W 21 c# string

当我有一个字符串,我想切割成从某个索引到某个索引的新字符串,我使用哪个函数?

如果字符串是:

ABCDEFG

这意味着当指定的两个索引为13时检索BCD.

Oli*_*bes 56

如果endIndex指向要包含在提取的子字符串中的最后一个字符:

int length = endIndex - startIndex + 1;
string piece = s.Substring(startIndex, length);
Run Code Online (Sandbox Code Playgroud)

如果endIndex指向所需子字符串后面的第一个字符(即到剩余文本的开头):

int length = endIndex - startIndex;
string piece = s.Substring(startIndex, length);
Run Code Online (Sandbox Code Playgroud)

有关Microsoft Docs上的官方说明,请参见String.Substring方法(Int32,Int32).


Rob*_*Rob 6

C# 8.0的新Range 特性使这成为可能。

在扩展方法string使用Range,以实现这一目标是:

public static class StringExtensions
{
    public static string SubstringByIndexes(this string value, int startIndex, int endIndex)
    {
        var r = Range.Create(startIndex, endIndex + 1);
        return value[r];
        /*
        // The content of this method can be simplified down to:

        return value[startIndex..endIndex + 1];

        // by using a 'Range Expression' instead of constructing the Range 'long hand'
        */
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:endIndex在构造 Range 时添加 1作为范围的结尾是不包含的,而不是包含的。

可以这样调用:

var someText = "ABCDEFG";

var substring = someText.SubstringByIndexes(1, 3);
Run Code Online (Sandbox Code Playgroud)

给人一种价值BCDsubstring