Rod
Rod

Reputation: 15477

best way to substring with variable length

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));

Upvotes: 4

Views: 7856

Answers (4)

T_D
T_D

Reputation: 3301

To me the most obvious solution would be:

var maxLength = 25;
var lineString = item.LineString.Trim();
if (lineString.length > maxLength) { //to check the length and only substring if needed
  lineString = lineString.Substring(0, maxLength);
}

Actually it will compile to very similar code as this solution from the existing answers:

var maxLength = 25;
var lineString = item.LineString.Trim();
lineString = lineString.Substring(0, Math.Min(maxLength , lineString.Length));

So it's not really a matter of performance, but rather personal preference and (very important) readability! Because less lines of codes are not always a better solution :)

Upvotes: 0

porcus
porcus

Reputation: 843

Interestingly, LINQ's Take method does almost exactly what you're trying to accomplish with the SubString length logic. While I'm confident its run-time efficiency isn't optimal, the following approach would also work:

string substring = new string(item.LineString.Trim().ToCharArray().Take(25).ToArray());

Just figured I'd put that out there, since the question was about "other ways" and not necessarily the "best way".

Upvotes: 1

porges
porges

Reputation: 30590

I'd use Math.Min:

var trimmed = item.LineString.Trim();
var substring = trimmed.Substring(0, Math.Min(25, trimmed.Length));

Upvotes: 9

annonymously
annonymously

Reputation: 4708

You can shorten it with:

item.LineString.Trim().Substring(0, Math.Min(25, item.LineString.Trim().Length));

Upvotes: 2

Related Questions