Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  "
like image 657
Graham Avatar asked Mar 29 '17 14:03

Graham


People also ask

How can I pad a string to a known length in C?

For 'C' there is alternative (more complex) use of [s]printf that does not require any malloc() or pre-formatting, when custom padding is desired. The trick is to use '*' length specifiers (min and max) for %s, plus a string filled with your padding character to the maximum potential length.

How to truncate the string in C?

To truncate a string in C, you can simply insert a terminating null character in the desired position. All of the standard functions will then treat the string as having the new length.

What do you mean by string padding in C?

Padding in string is adding a space or other character at the beginning or end of a string. String class has String. PadLeft() and String. PadRight() methods to pad strings in left and right sides. Padding in string is adding a space or other character at the beginning or end of a string.

What is the maximum length of a string in characters C#?

What is the max string length in C#? The maximum string length in C# is 2^31 characters. That's because String. Length is a 32-bit integer.


2 Answers

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);
like image 189
Dmitry Bychenko Avatar answered Sep 16 '22 11:09

Dmitry Bychenko


private string fixedLength(string input, int length){
    if(input.Length > length)
        return input.Substring(0,length);
    else
        return input.PadRight(length, ' ');
}
like image 35
waka Avatar answered Sep 19 '22 11:09

waka