convert saved string of numbers into an array of integers

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

i have a comma separated string of numbers inside of a var named num_str

the contents of num_str looks like this: "1,2,3,4,5" etc

i am looking for a way to add num_str to an expression to convert the sting of numbers contained therein to an array of integers

i want to make sure i can simply reference 'num_str' to get the numbers from instead of spelling it out like {"1,2,3,4,5"}

i have tried this, where 'num_str' contains the numbers

Dim test As String = Nothing Dim result() As Integer = Int32.TryParse(num_str.Split(","c)) For i = 0 To result.Length - 1    test += result(i) Next 

but that doesn't work

what i am looking for is a result with an array of numbers

回答1:

Dim totalValue = str.                  Split(","c).                  Select(Function(n) Integer.Parse(n)).                  Sum() 


回答2:

Try this to create integer array

Dim numbers = str.Split(","c).[Select](Function(n) Integer.Parse(n)).ToList() 

Then you can use the loop you are using at the moment to append value to string



回答3:

You can do it like this:

Dim num_str As String = ... Dim str() As String = num_str.Split(",") Dim result(str.Length - 1) As Integer For i = 0 To str.Length - 1     result(i) = str(i) Next 


回答4:

I was just working on this for a client, and I found an elegant little piece of code that will replace your single string value and effectively convert it to integer (or more precisely "double") very easily, and can be used for "find and convert" just as easily. I wrote a bunch of these into a GPA calculator that changes the letter grade entered into the GPA number format for math conversion and display without anything else but these three lines and a little loop.

For m = 0 To UBound(myArray) myArray(m) = Replace(myArray(m), "thisstring", 0.0)  'integer 0.0 can be any Next m 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!