如何将控制台打印三角形的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:
- Update the return type from
voidtostring - Use a
StringBuilderto efficiently build the multi-line content (string concatenation in loops creates unnecessary intermediate objects, soStringBuilderis far more efficient) - Replace
Console.WriteLinewith appending each row to theStringBuilder, including a newline character - 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
StringBuilderEfficiency: This is way better than looping withstring 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 forsb.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
StringBuilderinstead 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
相关产品推荐
相关产品推荐

