I've a String with Length = 100;
I need to center the text "Hello", in that string using whitespaces.
How can i do ?
thanks.
I've a String with Length = 100;
I need to center the text "Hello", in that string using whitespaces.
How can i do ?
thanks.
You can use the string padding methods and a little match to calcualte the center position:
var stringToCenter = "hello";
var totalLength = 100;
var centeredString =
stringToCenter.PadLeft(((totalLength - stringToCenter.Length) / 2)
+ stringToCenter.Length)
.PadRight(totalLength);
And you can move this logic into an extension method:
public static class StringExtensions{
public static string CenterString(this string stringToCenter, int totalLength)
{
return stringToCenter.PadLeft(((totalLength - stringToCenter.Length) / 2)
+ stringToCenter.Length)
.PadRight(totalLength);
}
}
And you can use it like
var centeredString = "hello".CenterString(100);
Demo .NETFiddle.
I would have added this as a comment to @nemesv's answer, but my lack of reputation on Stack Overflow prevents it.
The code in that answer causes more padding to be added on the right than the left. For example, in the code for that answer, the "h" in hello appears at the 43rd position instead of the 48th.
This revised code balances the padding.
var stringToCenter = "hello";
var stringToCenterLength = stringToCenter.Length;
var totalLength = 100;
var centeredString = stringToCenter.PadLeft(((totalLength - stringToCenterLength) / 2) + stringToCenterLength).PadRight(totalLength);
I've expanded @nemesv's answer to contain an overload accepting a padding character so you can get something like:
################################# Hello World! #################################
Code:
using System;
public class Program
{
public void Main()
{
Console.WriteLine(" Hello World! ".CenterString(80, '#'));
}
}
public static class StringExtensions
{
public static string CenterString(this string stringToCenter, int totalLength)
{
return stringToCenter.PadLeft(
((totalLength - stringToCenter.Length) / 2)
+ stringToCenter.Length).PadRight(totalLength);
}
public static string CenterString(this string stringToCenter,
int totalLength,
char paddingCharacter)
{
return stringToCenter.PadLeft(
((totalLength - stringToCenter.Length) / 2) + stringToCenter.Length,
paddingCharacter).PadRight(totalLength, paddingCharacter);
}
}
Example: .NETFiddle
You can calculate string lenght and then apply appropriate padding by:
"".PadLeft()
or "".PadRight()