1

I need to split a string like the one show below

13,14,15,16,17

into

13 14 15 16 17 and store them in an integer array

How can I do this?

I need this for my VB.NET project. Just the core concept will do

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Random User
  • 355
  • 4
  • 8
  • 19

1 Answers1

4

Use String.Split and Int32.Parse in this Linq query:

Dim intArr = str.Split(","c).Select(Function(s) Int32.Parse(s)).ToArray()

or, if you find the query-syntax easier:

Dim ints = From str In str.Split(","c)
           Select Int32.Parse(str)
dim intArr = ints.ToArray()

here the old approach without Linq but correctly sized array:

Dim strArr = str.Split(","c)
Dim intArr(strArr.Length - 1) As Int32
For i As Int32 = 0 To strArr.Length - 1
    intArr(i) = Int32.Parse(strArr(i))
Next
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • The sting will be entered in a text box control. should i store the text in a variable – Random User Jul 21 '13 at 10:46
  • The second code works great. Can you explain how this line of code works? – Random User Jul 21 '13 at 10:50
  • The ssecond approach is the same as the first, it's just a different syntax(query instead of method). Have a look: [Introduction to LINQ in Visual Basic](http://msdn.microsoft.com/en-us/library/vstudio/bb763068.aspx). – Tim Schmelter Jul 21 '13 at 19:52
  • How can I assign the values to a globally declared array? – Random User Jul 22 '13 at 09:00
  • @Dineshbabu: In .NET there is no concept of a "globally declared array". So what do you mean? – Tim Schmelter Jul 22 '13 at 09:20
  • @Dineshbabu: In .NET there is no concept of a "globally declared array". So what do you mean? http://stackoverflow.com/a/4529898/284240 – Tim Schmelter Jul 22 '13 at 09:46
  • I need the process of splitting under a condition. If the control comes out of the IF condition the variable is no longer accessible – Random User Jul 22 '13 at 12:23
  • @Dineshbabu: Sorry, it's difficult to understand the problem from the comment section. You might want to ask another question for this problem. – Tim Schmelter Jul 22 '13 at 12:26