📅  最后修改于: 2023-12-03 14:39:42.451000             🧑  作者: Mango
In C#, centering text can be achieved with the use of the String.PadLeft
and String.PadRight
methods.
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 "
.
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.
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.