繁体   English   中英

递归方法中的StackOverflow异常

[英]StackOverflow exception in a recursive method

我在C#中编写了一个应该缩进字符串的递归方法。 例如,这个字符串:

for (int i = 0; i < sb.Length; i++)
{
   if (sb[i] == '{')
   {
      startIndex = i;
      break;
   }
}

应转换为:

for (int i = 0; i < sb.Length; i++)
{
        if (sb[i] == '{')
        {
          startIndex = i;
          break;
        }
}

我的方法是(更新):

private static string IndentText(string t,bool first = true)
{
    if (first == false)
    {
        t = t.PadLeft(2);
    }

    int startIndex = t.IndexOf('{') + 1;
    int stopIndex = t.LastIndexOf('}') - 1;

    int blockLength = stopIndex - startIndex + 1;
    if (blockLength <= 1 )
    {
        return "";
    }

    string start = t.Substring(0, startIndex);
    string end = t.Substring(stopIndex + 1);
    string indentBlock = t.Substring(startIndex, blockLength);

    if (!CheckNestedBlocks(indentBlock))
    {
        return indentBlock;
    }

    return start + IndentText(indentBlock,false) + end;
}

private static bool CheckNestedBlocks(string t)
{
    for (int i = 0; i < t.Length; i++)
    {
        if (t[i] == '{')  // { and } always come in pairs, so I can check of only one of then
        {
            return true;
        }
    }
    return false;
}

但是我在mscorlib.dll遇到了StackOverflow异常

我的错是什么? 提前致谢。

顺便说一句 ,因为我认为我使这个问题变得复杂,是否有更好的(和工作)方法来缩进这样的字符串?

您不应该在递归调用中传递的“块”中包含大括号:

        if (t[i] == '{')
        {
            startIndex = i + 1;   // Start one character beyond {
            break;
        }

        // ...

        if (t[i] == '}')
        {
            stopIndex = i - 1;    // Stop one character prior to }
            break;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM