.NET equivalent of the old vb left(string, length) function
Here's an extension method that will do the job.
<System.Runtime.CompilerServices.Extension()> _
Public Function Left(ByVal str As String, ByVal length As Integer) As String
Return str.Substring(0, Math.Min(str.Length, length))
End Function
This means you can use it just like the old VB Left
function (i.e. Left("foobar", 3)
) or using the newer VB.NET syntax, i.e.
Dim foo = "f".Left(3) ' foo = "f"
Dim bar = "bar123".Left(3) ' bar = "bar"
Another one line option would be something like the following:
myString.Substring(0, Math.Min(length, myString.Length))
Where myString is the string you are trying to work with.
Add a reference to the Microsoft.VisualBasic library and you can use the Strings.Left which is exactly the same method.
Don't forget the null case:
public static string Left(this string str, int count)
{
if (string.IsNullOrEmpty(str) || count < 1)
return string.Empty;
else
return str.Substring(0,Math.Min(count, str.Length));
}
Use:
using System;
public static class DataTypeExtensions
{
#region Methods
public static string Left(this string str, int length)
{
str = (str ?? string.Empty);
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
str = (str ?? string.Empty);
return (str.Length >= length)
? str.Substring(str.Length - length, length)
: str;
}
#endregion
}
It shouldn't error, returns nulls as empty string, and returns trimmed or base values. Use it like "testx".Left(4) or str.Right(12);