'Substring is not working as expected if length is greater than length of String
I know if/else works, but I needed an alternative.
I am using
B = String.Concat(A.Substring(0, 40));
to capture the first 40 characters of a value.
If the value at A is more than 40, B is able to capture, but if the value of A is less than 40, there is no value being captured at B.
Solution 1:[1]
Quick and dirty:
A.Length > 40 ? A.Substring(0, 40) : A
Solution 2:[2]
Create an extension for it... Call it Truncate or Left, or whatever.
public static class MyExtensions
{
public static string Truncate(this string s, int length)
{
if(s.Length > length)
return s.Substring(0, length);
return s;
}
}
Then you can simply call it like so:
string B = A.Truncate(40);
Also note that you don't have to make it an extension method, although it would be cleaner.
In your StringTool class:
public static string Truncate(string value, int length)
{
if(value.Length > length)
return value.Substring(0, length);
return value;
}
And to call it:
string B = StringTool.Truncate(A, 40);
Solution 3:[3]
Use the below code to substring.
B = String.padright(40).Substring(0, 40)).Trim()
Solution 4:[4]
Extensions are best for problems like this one ;)
Mine have some dirty name, but everyone knows what it would do - this is an exception-safe substring:
public static string SubstringNoLongerThanSource(this string source, int startIndex, int maxLength)
{
return source.Substring(startIndex, Math.Min(source.Length - startIndex, maxLength));
}
Solution 5:[5]
B = string.Concat(A.Substring(0, Math.Min(40, A.Length)));
Solution 6:[6]
You can use Left from Microsoft.VisualBasic.Strings.
B = Microsoft.VisualBasic.Strings.Left(A, 40);
I don't know why you want to use Concat, anyway.
Solution 7:[7]
Another method using Take
B = new string(A.Take(40).ToArray())
Or extension method
public static string Left(this string value, int count)
{
return new string(value.Take(count).ToArray());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Me.Name |
| Solution 2 | Peter Mortensen |
| Solution 3 | Peter Mortensen |
| Solution 4 | Peter Mortensen |
| Solution 5 | irfandar |
| Solution 6 | Peter Mortensen |
| Solution 7 |
