猿问

为每个循环添加 1 个额外的字符到字符串

我有一个仅以 1 个字符“$”开头的字符串。我创建了一个运行 4 次的循环,每次,我希望我的字符串附加 1 个额外的“$”。所以当程序运行时,它应该会导致:


$

$$

$$$

$$$$

到目前为止,这是我的尝试:


        string draw = "";

        int counter = 0;


        while (counter < size) // size is 4

        {

            counter++;

            draw += "$\n";

        }

所以目前它导致:


$

$

$

$

一旦我得到这个太工作,我也想在它达到大小后每次减少 1。因此,如果大小为 4,则应如下所示:


$

$$

$$$

$$$$

$$$

$$

$


绝地无双
浏览 299回答 3
3回答

繁星点点滴滴

您可以使用以下代码&nbsp; &nbsp; &nbsp; &nbsp; int size = 4;&nbsp; &nbsp; &nbsp; &nbsp; string draw = "";&nbsp; &nbsp; &nbsp; &nbsp; while (size>0) // size is 4&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; size--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; draw += "$";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(draw);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; while (draw.Length > 1)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; size++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; draw = draw.Substring(0, draw.Length - 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(draw);&nbsp; &nbsp; &nbsp; &nbsp; }

MYYA

因为每次在 $ 字符后插入一个换行符。我认为您应该使用另一个变量来存储结果。此代码将起作用:int size = 4;string draw = "";int counter = 0;string res = "";while (counter < size) // size is 4{&nbsp; &nbsp; counter++;&nbsp; &nbsp; draw += "$";&nbsp; &nbsp; res += draw + "\n";}while (counter > 0){&nbsp; &nbsp; counter--;&nbsp; &nbsp; draw = draw.Remove(draw.Length - 1, 1);&nbsp; &nbsp; res += draw + "\n";}最好使用 StringBuilder 而不是仅仅连接一个字符串以获得更好的性能:int size = 4;int counter = 0;var sb = new StringBuilder();while (counter < size) // size is 4{&nbsp; &nbsp; counter++;&nbsp; &nbsp; sb.Append("$");&nbsp; &nbsp; Console.WriteLine(sb.ToString());}要从字符串末尾删除一个字符,您可以使用 Remove 方法,如下所示:while (counter > 0) // size is 4{&nbsp; &nbsp; counter--;&nbsp; &nbsp; sb.Remove(sb.Length - 1, 1);&nbsp; &nbsp; Console.WriteLine(sb.ToString());}

宝慕林4294392

你参考下面的代码,https://www.csharpstar.com/10-different-number-pattern-programs-in-csharp/&nbsp; &nbsp; &nbsp; &nbsp;Console.Write("Enter a number: ");&nbsp; &nbsp; &nbsp; &nbsp; int n = Convert.ToInt32(Console.ReadLine());&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine();&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 1; i < n; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j = 1; j <= i; j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.Write("$");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for(int i = n; i >= 0; i--)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j = 1; j <= i; j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.Write("$");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine();
随时随地看视频慕课网APP
我要回答