Skip to main content
 首页 » 编程设计

c#之递归方法中的 StackOverflow 异常

2024年02月13日18telwanggs

我用 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 异常

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

顺便说一下,因为我认为我使这个问题复杂化了,有没有更好(并且有效)的方法来像这样缩进字符串?

请您参考如下方法:

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

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