最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

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

C# crifan 5078浏览 0评论

【问题】

C#中,想要实现:

类似于这样的:

对于

hello world

可以格式化为:

****** hello wordl ******

—— hello world ——

且:

填充后的字符串的总长度

填充字符

是可以自己定义的。

 

【解决过程】

1.其实就是之前Python库中已经实现的类型的函数formatString

2.参考:

How-To Align String in Fixed Length String

最后是用如下代码:

    //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#的string的PadLeft和PadRight实现此处的中间对齐,左右填充的效果的。

转载请注明:在路上 » 【已解决】C#中实现字符串的中间对齐左右填充的效果

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.146 seconds, using 22.12MB memory