How to truncate or overlay a string to a fixed length in C #
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);
source to share
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);
source to share
You can use string.PadLeft
either string.PadRight
https://msdn.microsoft.com/en-us/library/66f6d830(v=vs.110).aspx
source to share