Get the first 5 elements  of string ? Console app

Dream_G
Dream_G used Ask the Experts™
on
Dear Experts,

I have a variable that contain this:
$V = 1,2,B,4,Yes,4,s,5,T,q,10125411,E

I want to to get the first 5 elements so the result would be like this:
$V = 1,2,B,4,Yes

Waiting for experts, thanks in advance.

Note: I am using vb.net and its Console application.

Regards.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jorge PaulinoIT Pro/Developer
Top Expert 2008

Commented:
Hi,
You can this way:

            Dim str As String = "$V = 1,2,B,4,Yes,4,s,5,T,q,10125411,E"
            Dim result As String() = str.Split(","c)
            If result.Length >= 5 Then
                Dim finalString As String = String.Format("{0},{1},{2},{3},{4}", result(0), result(1), result(2), result(3), result(4))
 
                Stop ' check the result
            End If

Open in new window

Author

Commented:
Hi jpaulino,

Thanks for your comment and code, the code work fine with 5 but it did not work for example with 4 or 3 because I have to write manually the (result(0)) ?

Is there way to made it automatically change the number of elements so I can change it from 5 to 4 ? Thanks.
IT Pro/Developer
Top Expert 2008
Commented:
Where you have:

            Dim str As String = "$V = 1,2,B,4,Yes,4,s,5,T,q,10125411,E"
            Dim result As String() = str.Split(","c)
            If result.Length >= 4 Then
 
                Dim finalString As String = String.Empty
                For x As Integer = 0 To 4
                    finalString &= result(x) & ","
                Next
 
                finalString = finalString.Remove(finalString.Length - 1, 1)
 
                Stop ' check the result
            End If

Open in new window

Author

Commented:
Thanks mate.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial