string.format 用法
我们用string.format 格式字符串的时候,通常只用到占位符,就是需要插入字符的位置,没有对其它有所研究,总体可以有三个方面的应用
插入位置
decimal temp = 20.4m; string s = String.Format("The temperature is {0}°C.", temp); Console.WriteLine(s); // Displays 'The temperature is 20.4°C.'
string s = String.Format("At {0}, the temperature is {1}°C.", DateTime.Now, 20.4); Console.WriteLine(s); // Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
插入间距
int[] years = { 2013, 2014, 2015 }; int[] population = { 1025632, 1105967, 1148203 }; var sb = new System.Text.StringBuilder(); sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population")); for (int index = 0; index < years.Length; index++) sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index])); Console.WriteLine(sb); // Result: // Year Population // // 2013 1,025,632 // 2014 1,105,967 // 2015 1,148,203
控制对齐,间距前加负号为左对齐,默认右对齐
默认情况下,如果指定字段宽度,则字符串在其字段中右对齐。若要在字段中左对齐字符串,请在字段宽度前面加上负号,例如定义一个 12 个字符的左对齐字段。{0,-12}
以下示例与上一个示例类似,不同之处在于它对标签和数据都左对齐。
int[] years = { 2013, 2014, 2015 }; int[] population = { 1025632, 1105967, 1148203 }; String s = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population"); for(int index = 0; index < years.Length; index++) s += String.Format("{0,-10} {1,-10:N0}\n", years[index], population[index]); Console.WriteLine($"\n{s}"); // Result: // Year Population // // 2013 1,025,632 // 2014 1,105,967 // 2015 1,148,203
控件格式,插入字符的同时格式化成所需要的格式比如时间
您可以使用格式字符串跟踪格式项中的索引,以控制对象的格式设置方式。例如,将“d”格式字符串应用于对象列表中的第一个对象。下面是一个包含单个对象和两个格式项的示例:{0:d}
string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now); Console.WriteLine(s); // Output similar to: 'It is now 4/10/2015 at 10:04 AM'
总结格式项
{index[,alignment][:formatString]}
格式项具有以下元素:
index
参数的从零开始的索引,其字符串表示形式将包含在字符串中的此位置。如果此参数为空,则将在字符串中的此位置包含一个空字符串
对齐
可选项。一个有符号整数,指示插入参数的字段的总长度以及它是右对齐(正整数)还是左对齐(负整数)。如果省略对齐方式,则相应参数的字符串表示形式将插入到没有前导空格或尾随空格的字段中。
如果参数太长超过对齐值,则忽略对齐方式,并将参数的字符串表示形式的长度用作字段宽度。
格式字符串
可选。一个字符串,指定相应参数的结果字符串的格式。如果省略 formatString,则会调用相应参数的无参数方法来生成其字符串表示形式