For example I entered the numbers "31572" in a textbox then it will get the number "5". Also if I enter numbers with the length of even numbers like "123752" then it will get the "37" which is in the center of the entered numbers. I have no idea what to with this, so I'm hoping someone gives me an idea. Thank you :)
Since you want to take from the string 2 chars when the string length is even and 1 char when it's odd, you just need to care about the remainder of the division by 2.
Using Integer division (3 \ 2 = 1
):
If String.Length Mod 2 = 0
, take 2 chars, starting from String.Length \ 2 - 1
If String.Length Mod 2 = 1
, take 1 chars, starting from String.Length \ 2
You may want to add a null check and just return the original string if the string length is less than 3 (when the string is "1"
or "12"
, return the string as it is).
Your code could be:
Dim result as string = GetCenterValue(TextBox1.Text)
Public Function GetCenterValue(content As String) As String
If String.IsNullOrEmpty(content) Then Return String.Empty
Dim sLength As Integer = content.Length
If sLength < 3 Then Return content
Return content.Substring(sLength \ 2 - (1 - sLength Mod 2), 2 - sLength Mod 2)
End Function
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments