Aligning a string in a space of 42 characters

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 client, the default amount of characters is 42.

texto="lb_NomeEmpresa.text";

This way you are aligning the left by simply setting the text in the file.

Atualmente:   |NOME EMPRESA           |
Esperado:     |     NOME EMPRESA      |
    
asked by anonymous 25.11.2014 / 14:19

1 answer

3

You need to do what is called padding . This until already exists in .NET but only on the left and the right, you need to do this 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);
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

Particularly I prefer to do this. But if you're sure you can not use this again then nothing prevents you from using 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 on in this OS response .

    
25.11.2014 / 14:25