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

178
Views
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 answers
Answer question

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 Report

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 Report

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 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!