📜  c# center text - C# (1)

📅  最后修改于: 2023-12-03 14:39:42.451000             🧑  作者: Mango

C# Center Text

In C#, centering text can be achieved with the use of the String.PadLeft and String.PadRight methods.

PadLeft and PadRight

Both PadLeft and PadRight take two arguments: the total width of the resulting string and the character to use for padding.

For example, the following code centers the string "Hello" within a total width of 10 characters using spaces for padding:

string text = "Hello";
int totalWidth = 10;
char paddingChar = ' ';
string centeredText = text.PadLeft((totalWidth + text.Length) / 2, paddingChar)
                          .PadRight(totalWidth, paddingChar);

The resulting centeredText is " Hello ".

CenterText Method

To make centering text easier, we can create a method that takes the text to center and the total width as arguments:

public static string CenterText(string text, int totalWidth, char paddingChar = ' ')
{
    return text.PadLeft((totalWidth + text.Length) / 2, paddingChar)
               .PadRight(totalWidth, paddingChar);
}

We can then use this method like so:

string text = "Hello";
int totalWidth = 10;
string centeredText = CenterText(text, totalWidth);

This will result in the same centeredText of " Hello " as before.

Conclusion

In summary, centering text in C# can be achieved with the String.PadLeft and String.PadRight methods. To make it easier, we can create a CenterText method that takes the text and total width as arguments.