c# - 如何使用 string.Format() 函数在 C# 中对齐字符串?

标签 c# .net string

输出为word文档(docx)。

我想使用 C# 4.0 string.Format 生成这样的输出:

string1: stringValue1,  string2:stringValue2
string4: stringValue4,  string5:stringValue5
string6: stringValue6,  string7:stringValue7
string8: stringValue8,  string9:stringValue9

我正在使用 string.Format("{0,-10} {1,-10}",string1,string2) 但它什么也没做。有没有办法使用 string.Format() 对齐字符串?我看到了 '\t' 解决方案,但如何将它添加到 string.Fornmat() 中?

这是我的代码和我的输出:

string titel = HttpUtility.HtmlEncode(docItem.Title);
                    string href = docItem.FullURL;
                    string title = string.Format("{0}", titel);
                    string author = docItem.Author;
                    string date = docItem.ChangedDate.Date.ToShortDateString();
                    CreateTextBoxConentParagraph(doc, string.Format("Title: <a href='{0}'>{1}</a> Author: {2} Geändert an: {3}",href,title.PadRight(20),author.PadRight(20), date),string.Format("chunkId_{0}", i++));

输出: 标题:作者:aaa Geändert an:19.04.2013

标题:第二作者:aaa Geändert an:18.04.2013

标题:slika 作者:aaa Geändert 时间:18.04.2013

标题:d m 作者:aaa Geändert an:18.04.2013

标题:Mathias 作者:aaa Geändert 时间:19.04.2013

标题:QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ 作者:aaa Geändert an:19.04.2013

最佳答案

尝试使用 PadLeftPadRight 方法。例如:

string.Format("{0} {1}",string1.PadRight(25),string2.PadRight(25)) 

您也可以使用字符来填充空格。来自 MSDN :

string str = "forty-two";
char pad = '.';
Console.WriteLine(str.PadRight(15, pad));    // Displays "forty-two......".
Console.WriteLine(str.PadRight(2,  pad));    // Displays "forty-two".

关于c# - 如何使用 string.Format() 函数在 C# 中对齐字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16104394/

相关文章:

c# - 将 List<Descendant> 转换为 List<Base> 的最简单方法

java - 为什么字符串输出中出现空值?

c# - 检查 Uppercase 函数是否有效

c# - 从 C# 中的添加/删除程序中删除应用程序的条目

c# - 使用 C# 加载网页并单击按钮

c# - 文件加载异常 : Could not load file or assembly (The assembly reference did not match the assembly definition found)

C++:使用运算符比较字符串的词典顺序

c# - DataGridView 中的选定行始终为 0

c# - 存在 LINQ 查询

.net - 在不同的应用程序域中加载实例