用已知的Start& amp; ENDINDEX

时间:2012-02-27 16:58:45

标签: c# string

当我有一个字符串,我想从某个索引切换到一个新字符串到某个索引时,我会使用哪个函数?

如果字符串是:

  

ABCDEFG

这意味着当指定的两个索引是 1 3 时,检索 BCD

5 个答案:

答案 0 :(得分:56)

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

int length = endIndex - startIndex + 1;
string piece = s.Substring(startIndex, length);

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

int length = endIndex - startIndex;
string piece = s.Substring(startIndex, length);

有关String.Substring Method (Int32, Int32)的官方说明,请参阅Microsoft Docs

答案 1 :(得分:1)

使用新的Range feature of C# 8.0,这成为可能。

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'
        */
    }
}

注意:在构造用于范围结尾的范围时,endIndex会添加1,这是排他的,而不是包含的。

可以这样称呼:

var someText = "ABCDEFG";

var substring = someText.SubstringByIndexes(1, 3);

substring中提供 BCD 的值。

答案 2 :(得分:1)

不幸的是,C#本身没有您需要的东西。 C#改为提供Substring(int startIndex,int length)。要实现Substring(int startIndex,int endIndex),您将需要自定义实现。以下扩展方法可以使可重用性更容易/更干净:

public static class Extensions
{
    public static string Substring2(this string value, int startIndex, int endIndex)
    {
        return value.Substring(startIndex, (endIndex - startIndex + 1));
    }
}

答案 3 :(得分:0)

子串字符串有两种方法..

1)

public string Substring(
    int startIndex
)

从此实例中检索子字符串。子字符串从指定的字符位置开始。

2)

public string Substring(
    int startIndex,
    int length
)

从此实例中检索子字符串。子字符串从指定的字符位置开始,并具有指定的长度。

答案 4 :(得分:-16)

您使用String.Substring

public string Substring(
  int startIndex,
  int length
)

公平地说,这是一个不太基本的问题,有非常容易接近的答案 - 我会给你怀疑你尝试了某些事情,它就是你在这里发现的不知何故;也许其他人可以受益(虽然我希望没有多少人需要它)。