C#中,类似于C中常用的spritf函数,是String.Format函数。
最简单的用法举例如下:
string spritfTestStr = String.Format("Test sprintf in C#, number={0:D}, string=\"{1:s}\", float={2:0.000}", 100, "crifan", Math.PI); //spritfTestStr = Test sprintf in C#, number=100, string="crifan", float=3.142
关于Format函数的更多的示例,可以参考微软官方文档:String.Format Method (String, Object)
关于其他更多不同类型的参数,比如日期,数值,枚举等,如何指定对应的格式,可以参考:
- For more information about the composite formatting feature supported by methods such as Format, AppendFormat, and some overloads of WriteLine, see Composite Formatting.
- For more information about numeric format specifiers, see Standard Numeric Format Strings and Custom Numeric Format Strings.
- For more information about date and time format specifiers, see Standard DateTime Format Strings and Custom DateTime Format Strings.
- For more information about enumeration format specifiers, see Enumeration Format Strings.
- For more information about formatting, see Formatting Types and Formatting Overview.
代码:
//input: [4] Valid: B0009IQZFM //output: ============================ [4] Valid: B0009IQZFM ============================= public string formatString(string strToFormat, char cPaddingChar = '*', int iTotalWidth = 80) { //auto added space strToFormat = " " + strToFormat + " "; //" [4] Valid: B0009IQZFM " //1. padding left int iPaddingLen = (iTotalWidth - strToFormat.Length)/2; int iLefTotalLen = iPaddingLen + strToFormat.Length; string strLefPadded = strToFormat.PadLeft(iLefTotalLen, cPaddingChar); //"============================ [4] Valid: B0009IQZFM " //2. padding right string strFormatted = strLefPadded.PadRight(iTotalWidth, cPaddingChar); //"============================ [4] Valid: B0009IQZFM =============================" return strFormatted; }