3

I've a String with Length = 100;

I need to center the text "Hello", in that string using whitespaces.

How can i do ?

thanks.

Yoann. B
  • 11,075
  • 19
  • 69
  • 111
  • Actually i found what i want (but in java) http://stackoverflow.com/questions/8154366/how-to-center-a-string-using-string-format – Yoann. B Nov 20 '11 at 09:42
  • take a look at http://www.csharp-examples.net/align-string-with-spaces/ – Glory Raj Nov 20 '11 at 09:44
  • @Yoann.B take a look at here http://stackoverflow.com/questions/644017/net-format-a-string-with-fixed-spaces i hope it will helps you.. – Glory Raj Nov 20 '11 at 09:57

4 Answers4

10

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359
  • What happens if ((totalLength - stringToCenter.Length) / 2) = 34.33 or some other non-integer value? – Tim Nov 20 '11 at 09:53
  • 1
    It won't happen (totalLength - stringToCenter.Length) / 2 will do integer division so the result will be always integer. – nemesv Nov 20 '11 at 09:57
  • I didn't know that (just tried it out myself). Nice to know. Thanks. – Tim Nov 20 '11 at 10:00
  • Downvoted as this answer actually gives the wrong result. It should insert 47 spaces at the start, but it only inserts 42. For the correct result see @Theophilus's answer – sgmoore Feb 07 '14 at 12:59
  • @sgmoore thanks for the comment, I fixed now my answer so it contains the correct calculation and also extended and formatted it when I was there. Sadly Theophilus posted his valuable comment as an answer so a was not notified about my error until now. – nemesv Feb 07 '14 at 13:11
  • If we apply a bit of algebra, we can see that the argument to `PadLeft()` can be simplified to `(totalLength + stringToCenter.Length) / 2` – Karl von L Aug 16 '20 at 18:24
7

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

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

Marcus Mangelsdorf
  • 2,852
  • 1
  • 30
  • 40
0

You can calculate string lenght and then apply appropriate padding by:

"".PadLeft() or "".PadRight()

Kamil Lach
  • 4,519
  • 2
  • 19
  • 20