I know if/else works, but I needed an alternative.
I am using
B = String.Concat(A.Substring(0, 40));
to capture the first 40 characters of a value.
If the value at A
is more than 40
, B
is able to capture, but if the value of A
is less than 40
, there is no value being captured at B
.
A quick one line would be:
B = A?.Length > 40 ? A.Substring(0, 40) : A;
which only implements the substring when the length is more than 40.
For the sake of redundancy, 40 would preferably be a variable of course. The use of '?.' prevents errors when 'A' is null.
As ean5533 mentioned A.Substring(0, Math.Min(40, A.Length))
can also be used. Same outcome, prevents the use of '40' twice, but will always invoke the substring function (not that that matters in this day of age)
For ease of use, an extension method can be created
public static string Truncate(this string value, int MaxLength) => value?.Length > MaxLength? value.Substring(0, MaxLength) : value;
Create an extension for it... Call it Truncate or Left, or whatever.
public static class MyExtensions
{
public static string Truncate(this string s, int length)
{
if(s.Length > length)
return s.Substring(0, length);
return s;
}
}
Then you can simply call it like so:
string B = A.Truncate(40);
Also note that you don't have to make it an extension method, although it would be cleaner.
In your StringTool class:
public static string Truncate(string value, int length)
{
if(value.Length > length)
return value.Substring(0, length);
return value;
}
And to call it:
string B = StringTool.Truncate(A, 40);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With