Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Cómo truncar o rellenar una cadena a una longitud fija en C#

¿Existe una forma sencilla de establecer una string en una longitud fija (en C#), ya sea truncándola o rellenándola con espacios ( ' ' ).

Por ejemplo:

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

después de establecer ambos en la longitud 5 , deberíamos tener:

 "abcde" "abc "
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Todo lo que necesita es PadRight seguido de Substring (siempre que la source no sea null ):

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

En caso de que la source pueda ser null :

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

0

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

0

Usaría la respuesta @waka, pero como método de extensión y verificación nula, así:

 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); }
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!