I'd like to write an extension method to the String
class so that if the input string to is longer than the provided length N
, only the first N
characters are to be displayed.
Here's how it looks like:
public static string TruncateLongString(this string str, int maxLength)
{
if (str.Length <= maxLength)
return str;
else
//return the first maxLength characters
}
What String.*()
method can I use to get only the first N
characters of str
?
The .NET Substring method is fraught with peril. I developed extension methods that handle a wide variety of scenarios. The nice thing is it preserves the original behavior, but when you add an additional "true" parameter, it then resorts to the extension method to handle the exception, and returns the most logical values, based on the index and length. For example, if length is negative, and counts backward. You can look at the test results with wide variety of values on the fiddle at: https://dotnetfiddle.net/m1mSH9. This will give you a clear idea on how it resolves substrings.
I always add these methods to all my projects, and never have to worry about code breaking, because something changed and the index is invalid. Below is the code.
I blogged about this back in May 2010 at: http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html
Simply:
if we are talking about validations also why we have not checked for null string entries. Any specific reasons?
I think below way help since IsNullOrEmpty is a system defined method and ternary operators have cyclomatic complexity = 1 while if() {} else {} has value 2.
Whenever I have to do string manipulations in C#, I miss the good old
Left
andRight
functions from Visual Basic, which are much simpler to use thanSubstring
.So in most of my C# projects, I create extension methods for them:
Note:
The
Math.Min
part is there becauseSubstring
throws anArgumentOutOfRangeException
when the input string's length is smaller than the requested length, as already mentioned in some comments under previous answers.Usage:
I added this in my project just because where I'm using it is a high chance of it being used in loops, in a project hosted online hence I didn't want any crashes if I could manage it. The length fits a column I have. It's C#7
Just a one line: