You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将控制台打印三角形的void方法改为返回多行字符串的string方法

Convert Console-Print Triangle Method to Return Multi-Line String

Got it! Let's walk through this modification with a concrete example, since I don't have your exact code. First, let's start with a typical void method that prints a triangle to the console—this mirrors the kind of logic you’re probably working with:

public static void PrintTriangle(int height)
{
    for (int i = 1; i <= height; i++)
    {
        // Build each row with i asterisks (adjust this for your triangle style)
        string row = new string('*', i);
        Console.WriteLine(row);
    }
}

Step-by-Step Modification

To turn this into a method that returns a multi-line string instead of printing directly, follow these simple steps:

  1. Update the return type from void to string
  2. Use a StringBuilder to efficiently build the multi-line content (string concatenation in loops creates unnecessary intermediate objects, so StringBuilder is far more efficient)
  3. Replace Console.WriteLine with appending each row to the StringBuilder, including a newline character
  4. Return the final built string from the StringBuilder

Here's the modified code:

using System.Text; // Don't forget this using directive for StringBuilder

public static string GetTriangle(int height)
{
    StringBuilder sb = new StringBuilder();
    
    for (int i = 1; i <= height; i++)
    {
        string row = new string('*', i);
        // Append the row plus a platform-agnostic newline
        sb.AppendLine(row);
    }
    
    // Return the full multi-line string
    return sb.ToString();
}

Key Details to Note

  • StringBuilder Efficiency: This is way better than looping with string result += row + "\n"—it avoids creating a new string object every iteration.
  • Newline Control: AppendLine() automatically uses the correct newline for your operating system (Windows uses \r\n, Unix uses \n). If you want explicit control, swap it for sb.Append(row + Environment.NewLine);.
  • Custom Triangle Adaptation: If your original method prints a different triangle (inverted, hollow, centered, etc.), the core logic stays identical—just keep building rows as before, but append them to the StringBuilder instead of printing.

To use this new method, you can do something like:

string triangle = GetTriangle(5);
Console.WriteLine(triangle); // Outputs the exact same triangle as the original void method

内容的提问来源于stack exchange,提问作者mattappdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:10:54