C#String.Substring等效于StringBuilder?

时间:2014-08-12 22:07:52

标签: c# substring stringbuilder

StringBuilder似乎没有Substring(start,len)方法......我在这里缺少什么?

3 个答案:

答案 0 :(得分:47)

StringBuilder类有一个特殊版本的ToString方法,它接受两个参数,与 Substring(startIndex,length)完全相同。

 StringBuilder sb = new StringBuilder("This is a Test");
 string test = sb.ToString(10, 4);
 Console.WriteLine(test);   // result = Test

答案 1 :(得分:1)

这些是你可以获得所需子字符串的所有方法:

StringBuilder b = new StringBuilder();
b.Append("some text to test out!");
string s = b.ToString(0, 6);
//or ....
char[] letters = new char[6];
b.CopyTo(0, letters, 0, 6);
string s1 = new string(letters);
//or
string s2 = null;
for (int i = 0; i < 6; i++)
{
   s2 += b[i];
}

答案 2 :(得分:1)

另一种方法,如果您不想构建整个字符串(StringBuilder.ToString())并获取子字符串:

  public static StringBuilder SubString(this StringBuilder input, int index, int length)
{
    StringBuilder subString = new StringBuilder();
    if (index + length - 1 >= input.Length || index < 0) 
    {
        throw new ArgumentOutOfRangeException("Index out of range!"); 
    }
    int endIndex = index + length;
    for (int i = index; i < endIndex; i++)
    {
        subString.Append(input[i]);
    }
    return subString;
}