mk9591
mk9591

Reputation: 11

VB.NET Substring get the last char position

I got the string. The length of the string is not fixed but the max is 16. At the length of 8 it must split to next string. How do I need to know split into string. Below is my current code. Please help. Thanks

   Dim input As String = "5210000000011754"

    If input.Length >= 8 Then
        Dim str1 As String = input.Substring(0, 8)
        Dim str2 As String = input.Substring(8, 8)

        Console.WriteLine(str1)
        Console.WriteLine(str2)
    End If

Upvotes: 0

Views: 748

Answers (3)

Sathish
Sathish

Reputation: 4487

change like this

 If input.Length >= 8 Then

    Dim str1 As String = input.Substring(0, 8)
    Dim str2 As String = input.Substring(8)

end if

if input string like this 521000000001 above code show

str1=52100000
str2=0001

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117064

Try it this way:

dim str1 = New String(input.Take(8).ToArray())
dim str2 = New String(input.Skip(8).ToArray())

This works with an empty string all the way up to the 16 character limit and splits at the 8 character mark.

It couldn't get simpler than that.

Upvotes: 3

dbasnett
dbasnett

Reputation: 11773

What if the string is less than 8?

    Dim input As String = "521"
    Dim str1 As String
    Dim str2 As String

    If input.Length >= 8 Then
        str2 = input.Substring(8)
    End If

    str1 = input.Substring(0, If(input.Length >= 8, 8, input.Length))

    Console.WriteLine(str1)
    Console.WriteLine(str2)

Upvotes: 0

Related Questions