C# 将字符串格式化为列
有没有一种很酷的方式来做这样的事情: Customer Name - City, State - ID Bob Whiley - Howesville, TN - 322 Marley Winchester - Old Towne, CA - 5653 Customer Name - City, State - ID Bob Whiley - Howesville, TN - 322 Marley Winchester - Old Towne, CA - 5653C# 将字符串格式化为列,c#,string,string-formatting,C#,String,String Formatting,有没有一种很酷的方式来做这样的事情: Customer Name - City, State - ID Bob Whiley - Howesville, TN - 322 Marley Winchester - Old Towne, CA - 5653 Customer Name - City, State - ID Bob Whiley - Howesville, TN - 322 Marley Winchester - Old Towne, CA
public partial class CustomerDataContract
{
public string DropDownDisplay
{
get
{
return Name + " - " + City + ", " + State + " - " + ID;
}
}
}
public string DropDownDisplay {
get {
return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
Name, City, State, ID);
}
}
我正在寻找一种更好的格式。有什么想法吗
这就是我的结局:
HttpContext.Current.Server.HtmlDecode(
String.Format("{0,-27} - {1,-15}, {2, 2} - {3,5}",
Name, City, State, ID)
.Replace(" ", " "));
HtmlDecode将更改为可以承受下拉列表中删除空格格式的空格。您可以使用
控制台指定文本占用的列数以及对齐方式。WriteLine
或使用字符串。Format
:
// Prints "--123 --"
Console.WriteLine("--{0,-10}--", 123);
// Prints "-- 123--"
Console.WriteLine("--{0,10}--", 123);
数字指定要使用的列数,符号指定对齐方式(-
表示左对齐,+
表示右对齐)。因此,如果您知道可用列的数量,您可以编写如下示例:
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
Customer Name - City, State - ID
Bob Whiley - Howesville, TN - 322
Marley Winchester - Old Towne, CA - 5653
public partial class CustomerDataContract
{
public string DropDownDisplay
{
get
{
return Name + " - " + City + ", " + State + " - " + ID;
}
}
}
public string DropDownDisplay {
get {
return String.Format("{0,-10} - {1,-10}, {2, 10} - {3,5}"),
Name, City, State, ID);
}
}
如果要根据整个列表计算列数(例如,最长的名称),然后,您需要提前获取该数字,并将其作为参数传递到您的
下拉显示中
-无法自动执行此操作。除了Tomas的答案之外,我只想指出,字符串插值可以在C#6或更高版本中使用
// with string format
var columnHeaders1 = string.Format($"|{0,-30}|{1,-4}|{2,-15}|{3,-30}|{4,-30}|{5,-30}|{6,-30}", "ColumnA", "ColumnB", "ColumnC", "ColumnD", "ColumnE", "ColumnF", "ColumnG");
// with string interpolation
var columnHeaders2 = $"|{"ColumnA",-30}|{"ColumnB",-4}|{"ColumnC",-15}|{"ColumnD",-30}|{"ColumnE",-30}|{"ColumnF",-30}|{"ColumnG",-30}";
回答得好!我认为它是有效的,但由于某些原因,当查看下拉列表时,它不起作用。我猜是有什么东西把多余的空间移走了(我需要找到一些方法来插入而不是空格。如果需要使用,只需在format.return string.format(“{0,-10}-{1,-10},{2,10}-{3,5}”)、Name、City、State、ID之后执行string.Replace即可;这就是我得到的结果:HttpContext.Current.Server.HtmlDecode(String.Format(“{0,-27}-{1,-15},{2,2}-{3,5}”,名称,城市,州,ID);