How to truncate or overlay a string to a fixed length in C #

Is there a one-liner way to set a string to a fixed length (in C #), either by truncating it or filling in spaces.

For example:

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

      

after setting as length 5, we should have:

"abcde"
"abc  "

      

+5


source to share


5 answers


All you need is this PadRight

, followed by Substring

(assuming source

not null

):

string source = ...
int length = 5;

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

      



The case source

may be null

:

string result = source == null 
  ? new string(' ', length) 
  : source.PadRight(length).Substring(0, length);

      

+7


source


private string fixedLength(string input, int length){
    if(input.Length > length)
        return input.Substring(0,length);
    else
        return input.PadRight(length, ' ');
}

      



+3


source


Have you tried s1.PadLeft (5);

you can also specify a fill character if you want something more than spaces

s1.PadLeft(6, '.');

      

Would give you: "abcdef."

do both:

var s1 = "1234567890";
var s2 = s1.SubString(5).PadLeft(5);

      

0


source


There are two options, one built-in and one custom.

You can use String.Format function like:

String.Format("{0:-5", str);

      

where str

is the string you want to format. {0}

represents this string, but :-5

indicates left-justification in a :-5

5-character string. To align it correctly, you just use :5

.

A custom one-liner str.Length > 5? str.Substring(0,5): str.PadRight(5);

will be str.Length > 5? str.Substring(0,5): str.PadRight(5);

str.Length > 5? str.Substring(0,5): str.PadRight(5);

, I believe it is more efficient than the other answers. If the string str

can be null

, you can use

str = str?.PadRight(5- str.Length) ?? new string(' ', 5);

      

0


source


You can use string.PadLeft

either string.PadRight

https://msdn.microsoft.com/en-us/library/66f6d830(v=vs.110).aspx

-1


source







All Articles