在C#中水平附加字符串 [英] appending string horizontally in c#
问题描述
我是C#的新手,正在此程序中尝试演示程序,我的预期输出是:
I am new to C# and trying a demo program in this program my intended output is:
Id 1 2 3 4 5 6 7 8 9
Roll # 1 2 3 4 5 6 7 8 9
这就是我尝试过的:
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Id ");
for (int i = 0; i < 10; i++)
{
sb.Append(i+" ");
}
sb.AppendLine();
sb.Append("Roll# ");
for (int i = 0; i < 10; i++)
{
sb.Append(i + " ");
}
Console.WriteLine(sb);
}
尽管它给了我想要的输出,但是在这里我必须遍历两次for循环.有什么方法可以使用某种C#字符串格式仅迭代一次就可以得到相同的输出?
though it gives me desired output but here I have to iterate through for loop twice. Is there any way by which only iterating once I can get the same output, using some string formatting of C#?
推荐答案
使用,以及字符串.Join()将先前创建的范围与字符串"
:
This can be done without explicit looping, using Enumerable.Range to "generate a sequence of integral numbers within a specified range", along with string.Join() to concatenate the previously created range with the string " "
:
// using System.Linq;
string range = string.Join(" ", Enumerable.Range(1, 10)); // "1 2 3 4 5 6 7 8 9 10"
sb.AppendLine($"Id {range}");
sb.AppendLine($"Roll# {range}");
如果您真的想使用 for
循环来构建序列,则可以构建自己的 Range
方法,例如:
If you really want to use a for
loop to build your sequence, you can build your own Range
method such as :
public static IEnumerable<int> Range(int min, int max)
{
if (min > max)
{
throw new ArgumentException("The min value can't be greater than the max");
}
for (int i = min; i <= max; i++)
{
yield return i;
}
}
然后像以前一样加入
:
var range = string.Join(" ", Range(1, 10));
sb.AppendLine($"Id {range}");
sb.AppendLine($"Roll# {range}");
或构建一个数组/列表/任何集合,然后使用 string.Join()
:
var arr = new int [10];
for (int i = 1; i <= 10; i++)
{
arr[i - 1] = i;
}
string range = string.Join(" ", arr);
sb.AppendLine($"Id {range}");
sb.AppendLine($"Roll# {range}");
或者直接在循环中构建一个字符串:
Or directly build a string in the loop :
var sbRange = new StringBuilder();
for (int i = 1; i <= 10; i++)
{
sbRange.Append($"{i} ");
}
// You can use a string and trim it (there is a space in excess at the end)
string range = sbRange.ToString().Trim();
sb.AppendLine($"Id {range}");
sb.AppendLine($"Roll# {range}");
这篇关于在C#中水平附加字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!