Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
How to truncate or pad a string to a fixed length in c#

Is there a one-liner way of setting a string to a fixed length (in C#), either by truncating it or padding it with spaces (' ').

For example:

string s1 = "abcdef";
string s2 = "abc";

after setting both to length 5, we should have:

"abcde"
"abc  "
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

All you need is PadRight followed by Substring (providing that source is not null):

string source = ...
int length = 5;

string result = source.PadRight(length).Substring(0, length);

In case source can be null:

string result = source == null 
  ? new string(' ', length) 
  : source.PadRight(length).Substring(0, length);
over 4 years ago · Santiago Trujillo Relatório

0

private string fixedLength(string input, int length){
    if(input.Length > length)
        return input.Substring(0,length);
    else
        return input.PadRight(length, ' ');
}
over 4 years ago · Santiago Trujillo Relatório

0

I would use the @waka answer, but as an extension method and null verification, like this:

    public static string FixedLength(this string value, int totalWidth, char paddingChar)
    {
        if (value is null)
            return new string(paddingChar, totalWidth);

        if (value.Length > totalWidth)
            return value.Substring(0, totalWidth);
        else
            return value.PadRight(totalWidth, paddingChar);
    }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda