Soo*_*tah 52 .net c# string string-formatting visual-studio-2010
好吧,我正在从我填充DataGridView的列表中获取数据,并将其导出到文本文件.我已经完成了将其导出为CSV的功能,并且也想做纯文本版本.
因为标题和其他元素的长度是可变的,当文件被保存然后在记事本中打开时,它看起来像一团糟,因为没有任何排列.
我想让输出看起来像这样:
Sample Title One Element One Whatever Else
Sample Title 2 Element 2 Whatever Else
S. T. 3 E3 Whatever Else
Run Code Online (Sandbox Code Playgroud)
我想我可以循环遍历每个元素以获得最长的元素的长度,这样我就可以计算要添加到每个剩余元素的空格数.
我的主要问题是:是否有一种优雅的方法可以将可变数量的字符添加到字符串中?有这样的东西会很高兴:myString.insert(index, charToInsert, howManyToInsert);
当然,我显然可以通过循环编写一个函数来执行此操作,但我想看看是否有更好的方法.
提前致谢!
-Sootah
Gab*_*abe 103
为此你可能想要myString.PadRight(totalLength, charToInsert).
有关详细信息,请参阅String.PadRight方法(Int32).
Jef*_*ado 41
使用String.Format()或TextWriter.Format()(取决于您实际写入文件的方式)并指定字段的宽度.
String.Format("{0,20}{1,15}{2,15}", "Sample Title One", "Element One", "Whatever Else");
Run Code Online (Sandbox Code Playgroud)
您也可以在插值字符串中指定字段的宽度:
$"{"Sample Title One",20}{"Element One",15}{"Whatever Else",15}"
Run Code Online (Sandbox Code Playgroud)
您知道,您可以使用适当的字符串构造函数创建一系列重复字符.
new String(' ', 20); // string of 20 spaces
Run Code Online (Sandbox Code Playgroud)
使用String.Format:
string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";
string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);
Run Code Online (Sandbox Code Playgroud)
格式中的{0,-20}第一个参数的长度固定为 20,负号保证字符串从左到右打印。
| 归档时间: |
|
| 查看次数: |
102270 次 |
| 最近记录: |