1.2.2. 字符串的中间对齐左右填充的效果

代码:


//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;
}

        

详见:【已解决】C#中实现字符串的中间对齐左右填充的效果