I want to substring a String from given start index and given substring length.
- if the string is empty then returns String.Empty
- if the string length is greater than start index then it substrings from given start index to given length...
- if the string length is less than start index then it returns from start index to last index
I just want to know if it can be improved and shorter with all these checks.
- if the string is null or empty
- if the start index is not less than zero
- if the start index is less than the length of given input string.
- if the given input string length is less than the desired substring length.
- if the given input string length is greater than the desired substring length.
Sample Input and Ouput for my program:
SplitEntity("", 1, 15) => ""
SplitEntity("abcdef", 0, 3) => "abc"
SplitEntity("abcdef", 3, 100) => "def"
SplitEntity("abcdef", 0, 100) => "abcdef"
SplitEntity("abcdef", -1, 100) => ""
My function is below:
Public Function SplitEntity(entity As String, startIndex As Integer,
subStringLength As Integer) As String
Dim spilttedString As String = String.Empty
If (Not String.IsNullOrEmpty(entity) AndAlso startIndex >=0 ) Then
If (entity.Length > startIndex) Then
If entity.Length >= (startIndex + subStringLength) Then
spilttedString = entity.Substring(startIndex, subStringLength)
ElseIf entity.Length < (startIndex + subStringLength) Then
spilttedString = entity.Substring(startIndex, (entity.Length - startIndex))
End If
End If
End If
Return spilttedString
End Function
substring
and usingsubstring
to do it. \$\endgroup\$ – tinstaafl Jun 29 '18 at 1:42