繁体   English   中英

Pad Left & Pad Right (Pad Center) 弦

[英]Pad Left & Pad Right (Pad Center) String

字符串既有PadLeftPadRight 我需要向左和向右填充(居中对齐)。 是否有一种标准化的方式来做到这一点,或者更好的是,一种实现相同目标的内置方式?

从来没听说过。 如果您发现自己经常使用它,则可以创建一个扩展方法。 假设您希望字符串位于中心,请使用以下内容

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

}

要使其成为扩展方法,请这样做:

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

顺便说一句,我只是将我的扩展包含在系统命名空间中——这取决于你做什么。

这是一个自定义实现,不需要重建字符串。

它也适用于奇数

    static string PadCenter(string text, int newWidth)
    {
        const char filler = ' ';
        int length = text.Length;
        int charactersToPad = newWidth - length;
        if (charactersToPad < 0) throw new ArgumentException("New width must be greater than string length.", "newWidth");
        int padLeft = charactersToPad/2 + charactersToPad%2;
        //add a space to the left if the string is an odd number
        int padRight = charactersToPad/2;

        StringBuilder resultBuilder = new StringBuilder(newWidth);
        for (int i = 0; i < padLeft; i++) resultBuilder.Insert(i, filler); 
        for (int i = 0; i < length; i++) resultBuilder.Insert(i + padLeft, text[i]); 
        for (int i = newWidth - padRight; i < newWidth; i++) resultBuilder.Insert(i, filler);
        return resultBuilder.ToString();
    }

这是@david-colwell扩展方法的一个稍微改进的版本,它也可以选择使用填充字符:

namespace System
{
    public static class StringExtensions
    {
        public static string PadSides(this string str, int totalWidth, char paddingChar = ' ')
        {
            int padding = totalWidth - str.Length;
            int padLeft = padding / 2 + str.Length;
            return str.PadLeft(padLeft, paddingChar).PadRight(totalWidth, paddingChar);
        }
    }
}

你可以自己做这个:

    string test = "Wibble";
    int padTo = 12;
    int padSize = (padTo - test.Length) / 2;
    if (padSize > 0) {
        test = test.Trim().PadLeft(test.Length + padSize).PadRight(test.Length + 2 * padSize);
    }

只需调整它以根据需要处理奇数填充长度,并在使您的生活更轻松的情况下将其作为扩展方法。

我认为这里有一点改进。

namespace System
{
    public static class StringExtensions
    {
        public static string PadCenter(this string str, int totalLength, char padChar = '\u00A0')
        {
            int padAmount = totalLength - str.Length;

            if (padAmount <= 1)
            {
                if (padAmount == 1)
                {
                    return str.PadRight(totalLength);
                }
                return str;
            }

            int padLeft = padAmount/2 + str.Length;

            return str.PadLeft(padLeft).PadRight(totalLength);
        }
    }
}

阅读本文后,我想提供另一个有用的功能(在打印中)。

这不应被视为对这个问题的回答,而是以此为基础。

基于@orad 的回答。

public static string PadSplit(string str1, string str2, int totalWidth, char paddingChar = ' ')
{
        string output;
        int paddingWidth = totalWidth - (str1.Length + str2.Length);
        output = string.Format("{0}{1}{2}", str1, string.Empty.PadCenter(paddingWidth, paddingChar), str2);
        return output;
}

PadSplit("David", "Wins", 16) => "David       Wins"
  /* Output looks like this
       *****Luke***** 
       *****Leia*****
       *****Han******
       **Chewbecca***  */

  string result = "";
   string names = "Luke,Leia,Han,Chewbecca";
   string[] charA = names.Split(',');

        for (int i = 0; i < charA.Length; i++)
        {
            int padLeft = (14 - charA[i].Length) / 2;
            string temp = charA[i].PadLeft(charA[i].Length + padLeft, '*');
            result += temp.PadRight(14, '*') + "\n";
        }
        Console.WriteLine(result);

你也可以像这样创建你的扩展:

public static string PadBoth(this string s, int padValue)
{
    return s.PadLeft(padValue).PadRight(padValue);
}

并在字符串上使用 PadBoth 方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM