Just curious if I can substring string only when String.Length is greater than or equal to 20 without using If or Try catch ?
Thanks!
Ummh what have you tried? Just check beforehand:
if(input.Length >= 20)
{
input = input.Substring(0,20);
}
If you really don't want to use an if statement you could use Linq which just obfuscates the solution though and is less performant in this case:
input = new string(input.Take(20).ToArray());
Or technically this doesn't use an if statement either:
input = input.Length >= 20 ? input.Substring(0,20) : input;
Use a string extension. It still uses an IF, however, it makes your code cleaner when using it.
public static string Left(this string input, int length)
{
string result = input;
if (input != null && input.Length > length)
{
result = input.Substring(0, length);
}
return result;
}
usage:
input = input.Left(20);
someString = someString.Substring(0,Math.Min(20,someString.Length));