As a non-.NET programmer I\'m looking for the .NET equivalent of the old Visual Basic function left(string, length)
. It was lazy in that it worked for any lengt
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);
I like doing something like this:
string s = "hello how are you";
s = s.PadRight(30).Substring(0,30).Trim(); //"hello how are you"
s = s.PadRight(3).Substring(0,3).Trim(); //"hel"
Though, if you want trailing or beginning spaces then you are out of luck.
I really like the use of Math.Min, it seems to be a better solution.
If you want to avoid using an extension method and prevent an under-length error, try this
string partial_string = text.Substring(0, Math.Min(15, text.Length))
// example of 15 character max
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));
}
Just in a very special case:
If you are doing this left and you will check the data with some partial string, for example:
if(Strings.Left(str, 1)=="*") ...;
Then you can also use C# instance methods, such as StartsWith
and EndsWith
to perform these tasks.
if(str.StartsWith("*"))...;
You could make your own:
private string left(string inString, int inInt)
{
if (inInt > inString.Length)
inInt = inString.Length;
return inString.Substring(0, inInt);
}
Mine is in C#, and you will have to change it for Visual Basic.