vb.net 使用 split 函数解析逗号分隔的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19215918/
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
using the split function to parse through a comma separated line
提问by user2835653
solved it on my own ...
自己解决了...
int1 = CInt(line.Split(CChar(","))(1))
To read the contents of a text file, line by line, i am using this code
要逐行读取文本文件的内容,我正在使用此代码
Using r As StreamReader = New StreamReader("0trace2.txt")
Dim line As String
line = r.ReadLine
Do While (Not line Is Nothing)
list.Add(line)
line = r.ReadLine
MsgBox(line)
Loop
End Using
however, the file has 4 comma separated values, all numbers. I need to extract each number as an integer. i tried the split method but i ran into an error
但是,该文件有 4 个逗号分隔值,均为数字。我需要将每个数字提取为整数。我尝试了 split 方法,但遇到了错误
Dim int1 as Integer
Dim int2 as Integer
Dim int3 as Integer
Dim int4 as Integer
Using r As StreamReader = New StreamReader("0trace2.txt")
Dim line As String
line = r.ReadLine
Do While (Not line Is Nothing)
list.Add(line)
line = r.ReadLine
'MsgBox(line)
int1 = CInt(line.Split(CChar(","))(1))
Loop
End Using
Thanks
谢谢
采纳答案by Yuriy Galanter
Assuming that you simple need to collect integers from a file with a structure like
假设您只需要从具有类似结构的文件中收集整数
1,2,3,4
5,6,7,8
9,10,11,12
you can use List(Of Integer) to collect them all, e.g.:
您可以使用 List(Of Integer) 来收集它们,例如:
Dim arr As New List(Of Integer)
Do While (Not line Is Nothing)
For Each s In line.split(",")
arr.Add(s)
Next
line = r.ReadLine
Loop
回答by Howard
Perhaps an easier approach would be something like:
也许更简单的方法是:
Dim IntList = Line.Split(","c).ToList.ConvertAll(Function(x) CInt(x))
or use linq
或使用 linq
Dim IntList = (From x In Line.Split(","c) Select CInt(x)).ToList
Note: Please no debate on CInt() vs Integer.Parse() vs Int32.Parse()
注意:请不要争论 CInt() 与 Integer.Parse() 与 Int32.Parse()

