Roy Osherove

View Original

TrimEnd() Vs. SubString()

Many developers have had to write a loop that writes out a comma separated value list. There's always the trick of how you make that last comma get removed from the end of that string. Usually, at the end of the loop, many developers will do something like this to remove the last char in the string:
 
out = out.Substring( 0, out.LastIndexOf( ',' )
 
However, there's a cleaner way to accomplish this task:
 
out = out.TrimEnd(',')
 
TrimeEnd can receive a char array so you can remove any unwanted chars from the end easily. The code is also more readable. And yes, there's a TrimStart() to match that function.