从特定位置开始将字符串连接在一起

本文关键字:字符串 连接 在一起 开始 定位 位置 | 更新日期: 2023-09-27 18:04:55

我想将多个字符串连接在一起,但要以一种整洁的方式显示。

例子
Record[1]    Title : xxxxxx      Date : dd/mm/yy
Record[1000]    Title : xxxxxx       Date : dd/mm/yy

如果我只是随着记录数的增加将字符串连接在一起,标题和日期将被推过屏幕,看起来很乱(如上所示)。我希望标题和日期总是在字符串中的某个位置(比如位置25)开始,所以无论记录长度的数字是标题和日期将对齐页面。

这个字符串将更新Treeview节点文本。

从特定位置开始将字符串连接在一起

考虑使用复合格式,特别是格式字符串的对齐参数

可选的align组件是一个带符号整数,指示首选的格式化字段宽度。如果对齐值小于格式化字符串的长度,则忽略对齐,并使用格式化字符串的长度作为字段宽度。如果对齐方式为正,则字段中的格式化数据为右对齐,如果对齐方式为负,则为左对齐。如果需要填充,则使用空白。如果指定对齐,则需要逗号。

var s="";
foreach (var item in col) {
    s += String.Format("Record[{0,-6}]    Title: {1,-15}    Date: {2}", item.ID, item.Title, item.Date);
}

使用StringBuilder提高效率的示例:

var sb = new StringBuilder();
foreach (var item in col) {
    sb.AppendFormat("Record[{0,-6}]    Title: {1,-15}    Date: {2}", item.ID, item.Title, item.Date);
}

您可以使用PadRight()来确保您的第一个字符串具有正确的长度:

var record = "Record[1]";
var title = "Title : xxxxxx Date : dd/mm/yy .";
var output = record.PadRight(25) + title;

这个适合我:

var paddingRecord = items.Select(x => x.Record.ToString().Length).Max();
var paddingTitle = items.Select(x => x.Title.Length).Max();
var result =
    String.Join(Environment.NewLine,
        items.Select(x =>
            String.Format(
                "Record[{0}]{1} Title : {2}{3} Date : {4:dd/MM/yy}",
                x.Record,
                "".PadLeft(paddingRecord - x.Record.ToString().Length),
                x.Title,
                "".PadLeft(paddingTitle - x.Title.Length),
                x.Date)));

我得到result:

Record[1]    Title : Foo     Date : 23/05/14
Record[1000] Title : Foo Bar Date : 23/05/14