kielou
kielou

Reputation: 437

How to convert array of string to array of integer

I'm trying to learn VB.

I want to convert the array of string to array of int then sort the new array of in and display it in one line.

Example: Input 2 4 1 2 5

Result: 1 2 2 4 5

I tried some solutions but didn't work

Here is my current code:

 Dim stringnum As String = "4 2 3"
    Dim result() As String = Split(stringnum, " ")

    Dim intList() As Integer

    intList = result.ConvertAll(Function(s) Integer.Parse(s))

    Console.WriteLine(Join(intList))
    Console.ReadLine()

Upvotes: 1

Views: 2337

Answers (3)

Trevor_G
Trevor_G

Reputation: 1331

Despite what others say and think, you still can't beat the classic method for performance...

Dim stringnum As String = "4 2 3"
Dim result() As String = Split(stringnum, " ")
Dim intList(Ubound(result)) as integer 
For I as integer = 0 to ubound(result)
    Integer.TryParse(Result(i), intList(I))
Next
Array.Sort(intList)
Console.WriteLine(String.Join(" ", intList))

I'm still genuinely of the opinion most of those shortcuts are just LAZY coding. Possibly with the exception of some of the sorting functions if you don't know how to do it right.

Upvotes: 0

Nkosi
Nkosi

Reputation: 247008

I want to convert the array of string to array of int then sort the new array of in and display it in one line.

Here it is mostly in one line using Linq

Imports System
Imports System.Linq

Public Module Module1

    Public Sub Main()
        Console.WriteLine("Input your numbers :")
        Dim stringnum = Console.ReadLine()        
        Console.WriteLine(String.Join(" ", stringnum.Split(" ").Select(Function(str) Integer.Parse(str)).OrderBy(Function(x) x)))
    End Sub
End Module

After splitting the string Split() select each number from the array and parse them to integers .Select(Function(str) Integer.Parse(str)). That should provide the integers that can now be ordered .OrderBy(Function(x) x) and joined together to get the resulting output

Upvotes: 0

Marc
Marc

Reputation: 993

Try the following

Console.WriteLine("Input your numbers :")

Dim stringnum = Console.ReadLine()
Dim result = Split(stringnum, " ")

Dim intList = Array.ConvertAll(result, Function(str) Integer.Parse(str))
Array.Sort(intList)

Console.WriteLine(String.Join(" ", intList))
Console.ReadLine()

Upvotes: 5

Related Questions