垫左,放大器;垫右(垫中心)字符串 [英] Pad Left & Pad Right (Pad Center) String

查看:113
本文介绍了垫左,放大器;垫右(垫中心)字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串既有 PadLeft PadRight 。我需要填充左,右(居中对齐)的。是否有这样做,或者通过标准的方式更好,但内置的实现同样的目标的方法是什么?

String has both PadLeft and PadRight. I am in need of padding both left and right (center justification). Is there a standardized way of doing this, or better yet, a built in way of achieving the same goal?

推荐答案

这并不是说我知道。如果你看到自己使用了很多,你可以创建一个扩展方法。假设你希望你的字符串在中心结束了,使用类似以下

Not that I know of. You can create an extension method if you see yourself using it a lot. Assuming you want your string to end up in the center, use something like the following

public string PadBoth(string source, int length)
{
    int spaces = length - source.Length;
    int padLeft = spaces/2 + source.Length;
    return source.PadLeft(padLeft).PadRight(length);

}

为使这是一个扩展方法,这样做就像这样:

To make this an extension method, do it like so:

namespace System
{
    public static class StringExtensions
    {
        public static string PadBoth(this string str, int length)
        {
            int spaces = length - str.Length;
            int padLeft = spaces / 2 + str.Length;
            return str.PadLeft(padLeft).PadRight(length);
        }
    }
}



顺便说一句,我只是包括我在系统命名空间扩展 - 这取决于你怎么办

As an aside, I just include my extensions in the system namespace - it's up to you what you do.

这篇关于垫左,放大器;垫右(垫中心)字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆