格式化字符串转换成列 [英] Format a string into columns
问题描述
有没有采取像这样一个很酷的方式:
Is there a cool way to take something like this:
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
和它格式化为这样的事情:
and format it to something like this:
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
使用字符串格式的命令?
Using string format commands?
我并不是太挂在做什么,如果一个是很长。例如,这将是确定由我:
I am not too hung up on what to do if one is very long. For example this would be ok by me:
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
Super Town person - Long Town Name, WA- 45648
要提供一些背景。我有一个下拉框,显示的信息非常相似这一点。现在我的code创建的项目在下拉看起来是这样的:
To provide some context. I have a drop down box that shows info very similar to this. Right now my code to create the item in the drop down looks like this:
public partial class CustomerDataContract
{
public string DropDownDisplay
{
get
{
return Name + " - " + City + ", " + State + " - " + ID;
}
}
}
我要寻找一种方式来格式化这个更好。任何想法?
I am looking for a way to format this better. Any ideas?
这是我结束了:
HttpContext.Current.Server.HtmlDecode(
String.Format("{0,-27} - {1,-15}, {2, 2} - {3,5}",
Name, City, State, ID)
.Replace(" ", " "));
该HtmlDe code改变 以能够承受该空间除去的下拉列表的格式的空间中。
The HtmlDecode changes the to a space that can withstand the space removing formatting of the dropdown list.
推荐答案
您可以指定使用由文本占用以及对齐列数 Console.WriteLine
或使用的String.Format
:
You can specify the number of columns occupied by the text as well as alignment using Console.WriteLine
or using String.Format
:
// Prints "--123 --"
Console.WriteLine("--{0,-10}--", 123);
// Prints "-- 123--"
Console.WriteLine("--{0,10}--", 123);
数目指定要使用的列数和符号指定对齐( -
左对齐, +
右对齐)。所以,如果你知道列的可用数量,你可以写例如是这样的:
The number specifies the number of columns you want to use and the sign specifies alignment (-
for left alignment, +
for right alignment). So, if you know the number of columns available, you could write for example something like this:
public string DropDownDisplay {
get {
return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
Name, City, State, ID);
}
}
如果你想计算的列基于整个列表上的号码(如:最长的名称),那么你就需要得到事先的数量和它作为参数传递到你的 DropDownDisplay
- 有没有办法来自动执行此操作。
If you'd like to calculate the number of columns based on the entire list (e.g. the longest name), then you'll need to get that number in advance and pass it as a parameter to your DropDownDisplay
- there is no way to do this automatically.
这篇关于格式化字符串转换成列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!