Console.WriteLine을 사용하여 열의 텍스트를 어떻게 정렬 할 수 있습니까?
일종의 열 표시가 있지만 끝 두 열이 올바르게 정렬되지 않은 것 같습니다. 이것은 내가 현재 가지고있는 코드입니다.
Console.WriteLine("Customer name "
+ "sales "
+ "fee to be paid "
+ "70% value "
+ "30% value");
for (int DisplayPos = 0; DisplayPos < LineNum; DisplayPos = DisplayPos + 1)
{
seventy_percent_value = ((fee_payable[DisplayPos] / 10.0) * 7);
thirty_percent_value = ((fee_payable[DisplayPos] / 10.0) * 3);
Console.WriteLine(customer[DisplayPos] + " "
+ sales_figures[DisplayPos] + " "
+ fee_payable[DisplayPos] + " "
+ seventy_percent_value + " "
+ thirty_percent_value);
}
저는 신인 프로그래머라서 모든 조언을 이해하지 못할 수도 있지만 조언이 있다면 대단히 감사하겠습니다!
임의의 공백 문자열이있는 열에 텍스트를 수동으로 정렬하는 대신 \t
각 출력 문자열에 실제 탭 ( 이스케이프 시퀀스)을 포함해야 합니다.
Console.WriteLine("Customer name" + "\t"
+ "sales" + "\t"
+ "fee to be paid" + "\t"
+ "70% value" + "\t"
+ "30% value");
for (int DisplayPos = 0; DisplayPos < LineNum; DisplayPos++)
{
seventy_percent_value = ((fee_payable[DisplayPos] / 10.0) * 7);
thirty_percent_value = ((fee_payable[DisplayPos] / 10.0) * 3);
Console.WriteLine(customer[DisplayPos] + "\t"
+ sales_figures[DisplayPos] + "\t"
+ fee_payable + "\t\t"
+ seventy_percent_value + "\t\t"
+ thirty_percent_value);
}
이 시도
Console.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}",
customer[DisplayPos],
sales_figures[DisplayPos],
fee_payable[DisplayPos],
seventy_percent_value,
thirty_percent_value);
여기서 중괄호 안의 첫 번째 숫자는 인덱스이고 두 번째는 정렬입니다. 두 번째 숫자의 부호는 문자열을 왼쪽 또는 오른쪽 정렬해야하는지 여부를 나타냅니다. 왼쪽 정렬에는 음수를 사용하십시오.
또는 http://msdn.microsoft.com/en-us/library/aa331875(v=vs.71).aspx 를 참조 하십시오.
roya의 답변에 추가하기 위해. C # 6.0에서는 이제 문자열 보간을 사용할 수 있습니다.
Console.WriteLine($"{customer[DisplayPos],10}" +
$"{salesFigures[DisplayPos],10}" +
$"{feePayable[DisplayPos],10}" +
$"{seventyPercentValue,10}" +
$"{thirtyPercentValue,10}");
이것은 실제로 모든 추가 비용없이 한 줄이 될 수 있습니다. 저는 이것이 이렇게 읽기가 조금 더 쉬워 진다고 생각합니다.
또한 System.Console에서 정적 가져 오기를 사용하여 다음을 수행 할 수 있습니다.
using static System.Console;
WriteLine(/* write stuff */);
나는 아주 오래된 스레드를 알고 있지만 제안 된 솔루션은 더 긴 문자열이있을 때 완전히 자동이 아니 었습니다.
따라서 완전히 자동으로 수행되는 작은 도우미 메서드를 만들었습니다. 각 배열이 라인과 배열의 각 요소, 물론 라인의 요소를 나타내는 문자열 배열 목록을 전달하십시오.
이 방법은 다음과 같이 사용할 수 있습니다.
var lines = new List<string[]>();
lines.Add(new[] { "What", "Before", "After"});
lines.Add(new[] { "Name:", name1, name2});
lines.Add(new[] { "City:", city1, city2});
lines.Add(new[] { "Zip:", zip1, zip2});
lines.Add(new[] { "Street:", street1, street2});
var output = ConsoleUtility.PadElementsInLines(lines, 3);
도우미 메서드는 다음과 같습니다.
public static class ConsoleUtility
{
/// <summary>
/// Converts a List of string arrays to a string where each element in each line is correctly padded.
/// Make sure that each array contains the same amount of elements!
/// - Example without:
/// Title Name Street
/// Mr. Roman Sesamstreet
/// Mrs. Claudia Abbey Road
/// - Example with:
/// Title Name Street
/// Mr. Roman Sesamstreet
/// Mrs. Claudia Abbey Road
/// <param name="lines">List lines, where each line is an array of elements for that line.</param>
/// <param name="padding">Additional padding between each element (default = 1)</param>
/// </summary>
public static string PadElementsInLines(List<string[]> lines, int padding = 1)
{
// Calculate maximum numbers for each element accross all lines
var numElements = lines[0].Length;
var maxValues = new int[numElements];
for (int i = 0; i < numElements; i++)
{
maxValues[i] = lines.Max(x => x[i].Length) + padding;
}
var sb = new StringBuilder();
// Build the output
bool isFirst = true;
foreach (var line in lines)
{
if (!isFirst)
{
sb.AppendLine();
}
isFirst = false;
for (int i = 0; i < line.Length; i++)
{
var value = line[i];
// Append the value with padding of the maximum length of any value for this element
sb.Append(value.PadRight(maxValues[i]));
}
}
return sb.ToString();
}
}
이것이 누군가를 돕기를 바랍니다. 소스는 내 블로그의 게시물에서 가져온 것입니다. http://dev.flauschig.ch/wordpress/?p=387
열 사이의 공백 대신 탭을 사용하거나 형식 문자열에서 열의 최대 크기를 설정할 수 있습니다.
서식 지정에 도움이 될 수있는 여러 NuGet 패키지가 있습니다. 경우에 따라의 기능으로 string.Format
충분하지만 적어도 내용에 따라 열 크기를 자동으로 조정할 수 있습니다.
ConsoleTableExt
ConsoleTableExt 는 그리드 선이없는 테이블을 포함하여 테이블의 형식을 지정할 수있는 간단한 라이브러리입니다. (더 많이 사용되는 패키지 인 ConsoleTables 는 테두리없는 테이블을 지원하지 않는 것 같습니다.) 다음은 내용에 따라 크기가 조정 된 개체 목록의 형식을 지정하는 예입니다.
ConsoleTableBuilder
.From(orders
.Select(o => new object[] {
o.CustomerName,
o.Sales,
o.Fee,
o.Value70,
o.Value30
})
.ToList())
.WithColumn(
"Customer",
"Sales",
"Fee",
"70% value",
"30% value")
.WithFormat(ConsoleTableBuilderFormat.Minimal)
.WithOptions(new ConsoleTableBuilderOption { DividerString = "" })
.ExportAndWriteLine();
CsConsoleFormat
If you need more features than that, any console formatting can be achieved with CsConsoleFormat.† For example, here's formatting of a list of objects as a grid with fixed column width of 10, like in the other answers using string.Format
:
ConsoleRenderer.RenderDocument(
new Document { Color = ConsoleColor.Gray }
.AddChildren(
new Grid { Stroke = LineThickness.None }
.AddColumns(10, 10, 10, 10, 10)
.AddChildren(
new Div("Customer"),
new Div("Sales"),
new Div("Fee"),
new Div("70% value"),
new Div("30% value"),
orders.Select(o => new object[] {
new Div().AddChildren(o.CustomerName),
new Div().AddChildren(o.Sales),
new Div().AddChildren(o.Fee),
new Div().AddChildren(o.Value70),
new Div().AddChildren(o.Value30)
})
)
));
It may look more complicated than pure string.Format
, but now it can be customized. For example:
If you want to auto-size columns based on content, replace
AddColumns(10, 10, 10, 10, 10)
withAddColumns(-1, -1, -1, -1, -1)
(-1
is a shortcut toGridLength.Auto
, you have more sizing options, including percentage of console window's width).If you want to align number columns to the right, add
{ Align = Right }
to a cell's initializer.If you want to color a column, add
{ Color = Yellow }
to a cell's initializer.You can change border styles and more.
† CsConsoleFormat was developed by me.
I really like those libraries mentioned here but I had an idea that could be simpler than just padding or doing tons of string manipulations,
You could just manually set your cursor using the maximum string length of your data. Here's some code to get the idea (not tested):
var column1[] = {"test", "longer test", "etc"}
var column2[] = {"data", "more data", "etc"}
var offset = strings.OrderByDescending(s => s.Length).First().Length;
for (var i = 0; i < column.Length; i++) {
Console.Write(column[i]);
Console.CursorLeft = offset + 1;
Console.WriteLine(column2[i]);
}
you could easily extrapolate if you have more rows.
참고URL : https://stackoverflow.com/questions/4449021/how-can-i-align-text-in-columns-using-console-writeline
'IT박스' 카테고리의 다른 글
Android ListView 선택한 항목이 강조 표시됨 (0) | 2020.10.20 |
---|---|
플래시 기반 웹 사이트가 왜 그렇게 나쁜가요? (0) | 2020.10.20 |
ASP.NET MVC 4는 들어오는 모든 요청을 가로 챕니다. (0) | 2020.10.19 |
CSS와 함께 FontAwesome 또는 Glyphicons 사용 : before (0) | 2020.10.19 |
MySQL에서 가장 가까운 정수로 내림하는 방법은 무엇입니까? (0) | 2020.10.19 |