vb.net 将保存的数字字符串转换为整数数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19121595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:18:14  来源:igfitidea点击:

convert saved string of numbers into an array of integers

arraysvb.net

提问by user2835653

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

我在名为 num_str 的 var 中有一个逗号分隔的数字字符串

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

num_str 的内容如下所示:“1,2,3,4,5”等

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

我正在寻找一种将 num_str 添加到表达式的方法,以将其中包含的数字串转换为整数数组

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"}

我想确保我可以简单地引用 'num_str' 来获取数字,而不是像 {"1,2,3,4,5"} 那样拼写出来

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

我试过这个,其中 'num_str' 包含数字

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

我正在寻找的是带有数字数组的结果

回答by jcwrequests

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

回答by huMpty duMpty

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

然后您可以使用您目前使用的循环将值附加到字符串

回答by srka

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

回答by Chris Baxter

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.

我只是在为一个客户处理这个问题,我发现了一段优雅的小代码,可以很容易地替换你的单个字符串值并有效地将它转换为整数(或更准确地说是“双精度”),并且可以用于“查找并转换”同样容易。我将其中的一堆写入 GPA 计算器,该计算器将输入的字母等级更改为 GPA 数字格式以进行数学转换和显示,除了这三行和一个小循环外,没有其他任何东西。

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