Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to substring with variable length

Tags:

c#

I want to substring a variable length string with leading spaces to 25 or less characters. i got it to work but looking for other ways?

  ...  item.LineString.Trim().Substring(0, 
item.LineString.Trim().Length > 25 ? 25 : item.LineString.Trim().Length));
like image 387
Rod Avatar asked Oct 28 '25 04:10

Rod


2 Answers

I'd use Math.Min:

var trimmed = item.LineString.Trim();
var substring = trimmed.Substring(0, Math.Min(25, trimmed.Length));
like image 59
porges Avatar answered Oct 30 '25 03:10

porges


You can shorten it with:

item.LineString.Trim().Substring(0, Math.Min(25, item.LineString.Trim().Length));
like image 27
annonymously Avatar answered Oct 30 '25 03:10

annonymously



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!