How to align a string in a 42-character space

Asked

Viewed 1,746 times

3

I am generating a text file and have to align the company name to the center, but the company name will vary for each customer, the default amount of characters are 42.

texto="lb_NomeEmpresa.text";

this way is aligning the left, simply setting the text in the file.

Atualmente:   |NOME EMPRESA           |
Esperado:     |     NOME EMPRESA      |
  • You could subtract 42 from the number of characters of the company name and divide the result by 2, because there, you will find how many spaces to put in the beginning and end.

  • I’ll do this logic, thank you

1 answer

3


You need to do what you call it padding. This up to already exists on . NET but only left and right, you need it to do in both, so the ideal would be to create an extension method for this.

using System;
using static System.Console;

public class Program {
    public static void Main() {
        Write($"|{("Hello World".PadBoth(42))}|");
    }
}

namespace System {
    public static class StringExt {
        public static string PadBoth(this string str, int length, char character = ' ') => str.PadLeft((length - str.Length) / 2 + str.Length, character).PadRight(length, character);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Particularly I prefer to do this way. But if you are sure (can you have?) that you will not use this again nothing prevents you from using the code inline instead of creating a method.

The extension method you can put into a library with a collection of them and use in all your applications.

Solution based in that OS response.

  • But that would align the left Bigown and the intention is to line up at the center of the 42 caracateres.

  • Now that I saw that the question is all weird because of the formatting. I will change to do what he wants.

  • I tried to simulate how is generating the text and it was not as expected, he took out the spaces

  • @bigown when copying code from somewhere put the credits. http://stackoverflow.com/questions/17590528/pad-left-pad-right-pad-centerstring

  • @Toncunha Don’t be hasty, I haven’t finished yet.

  • Just to complement, no . Netfiddle, the spaces that are added after the name, do not appear. To better visualize, just swap the space for some other character.

  • @Emanuelsn You’re talking about the old version.

  • @Brunorodrigues tried now with this version of the answer?

  • @mustache I’ll try now!

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.