vb.net 如何从逗号分隔的字符串中选择一个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14651151/
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
How to select a value from a comma delimited string?
提问by gromit1
I have a string that contains comma delimited text. The comma delimited text comes from an excel .csv file so there are hundreds of rows of data that are seven columns wide. An example of a row from this file is:
我有一个包含逗号分隔文本的字符串。逗号分隔的文本来自 excel .csv 文件,因此有数百行七列宽的数据。此文件中的一行示例是:
2012-10-01,759.05,765,756.21,761.78,3168000,761.78
2012-10-01,759.05,765,756.21,761.78,3168000,761.78
I want to search through the hundreds of rows by the date in the first column. Once I find the correct row I want to extract the number in the first position of the comma delimited string so in this case I want to extract the number 759.05 and assign it to variable "Open".
我想按第一列中的日期搜索数百行。一旦找到正确的行,我想提取逗号分隔字符串第一个位置的数字,因此在这种情况下,我想提取数字 759.05 并将其分配给变量“Open”。
My code so far is:
到目前为止我的代码是:
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
Dim Year As String = 2012
Dim Quarter As String = Q4
If Quarter = "Q4" Then
Dim Open As Integer =
End If
Once I can narrow it down to the right row I think something like row.Split(",")(1).Trim) might work.
一旦我可以将其缩小到正确的行,我认为像 row.Split(",")(1).Trim) 这样的东西可能会起作用。
I've done quite a bit of research but I can't solve this on my own. Any suggestions!?!
我已经做了很多研究,但我无法自己解决这个问题。有什么建议!?!
ADDITIONAL INFORMATION:
附加信息:
Private Function RequestWebData(ByVal pstrURL As String) As String
Dim objWReq As WebRequest
Dim objWResp As WebResponse
Dim strBuffer As String
'Contact the website
objWReq = HttpWebRequest.Create(pstrURL)
objWResp = objWReq.GetResponse()
'Read the answer from the Web site and store it into a stream
Dim objSR As StreamReader
objSR = New StreamReader(objWResp.GetResponseStream)
strBuffer = objSR.ReadToEnd
objSR.Close()
objWResp.Close()
Return strBuffer
End Function
MORE ADDITIONAL INFORMATION:
更多附加信息:
A more complete picture of my code
我的代码的更完整图片
Dim tickerArray() As String = {"GOOG", "V", "AAPL", "BBBY", "AMZN"}
For Each tickerValue In Form1.tickerArray
Dim strURL As String
Dim strBuffer As String
'Creates the request URL for Yahoo
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
'Create Array
Dim lines As Array = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
'Add Rows to DataTable
dr = dt.NewRow()
dr("Ticker") = tickerValue
For Each columnQuarter As DataColumn In dt.Columns
Dim s As String = columnQuarter.ColumnName
If s.Contains("-") Then
Dim words As String() = s.Split("-")
Dim Year As String = words(0)
Dim Quarter As String = words(1)
Dim MyValue As String
Dim Open As Integer
If Quarter = "Q1" Then MyValue = Year & "-01-01"
If Quarter = "Q2" Then MyValue = Year & "-04-01"
If Quarter = "Q3" Then MyValue = Year & "-07-01"
If Quarter = "Q4" Then MyValue = Year & "-10-01"
For Each line In lines
Debug.WriteLine(line)
If line.Split(",")(0).Trim = MyValue Then Open = line.Split(",")(1).Trim
dr(columnQuarter) = Open
Next
End If
Next
dt.Rows.Add(dr)
Next
Right now in the For Each line in linesloop, Debug.WriteLine(line)outputs 2,131 lines:
现在在For Each line in lines循环中,Debug.WriteLine(line)输出 2,131 行:
From
从
Date,Open,High,Low,Close,Volume,Adj Close
2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74
2013-02-04,767.69,770.47,758.27,759.02,3040500,759.02
2013-02-01,758.20,776.60,758.10,775.60,3746100,775.60
All the way to...
一路到...
2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
But, what I expect is for Debug.WriteLine(line)to output one line at a time in the For Each line in linesloop. So I would expect the first output to be Date,Open,High,Low,Close,Volume,Adj Closeand the next output to be 2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74. I expect this to happen 2,131 times until the last output is 2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
但是,我期望的是Debug.WriteLine(line)在For Each line in lines循环中一次输出一行。所以我希望第一个输出是Date,Open,High,Low,Close,Volume,Adj Close,下一个输出是2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74. 我希望这会发生 2,131 次,直到最后一次输出2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
回答by Steven Doggart
You could loop through the lines and call String.Splitto parse the columns in each line, for instance:
您可以遍历行并调用String.Split以解析每行中的列,例如:
Dim lines() As String = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Next
However, sometimes CSV isn't that simple. For instance, a cell in a spreadsheet could contain a comma character, in which case it would be represented in CSV like this:
但是,有时 CSV 并没有那么简单。例如,电子表格中的单元格可能包含逗号字符,在这种情况下,它将以 CSV 格式表示如下:
example cell 1,"example, with comma",example cell 3
To make sure you're properly handling all possibilities, I'd recommend using the TextFieldParserclass. For instance:
为确保您正确处理所有可能性,我建议使用TextFieldParser类。例如:
Using parser As New TextFieldParser(New StringReader(strBuffer))
parser.TextFieldType = FieldType.Delimited
parser.SetDelimiters(",")
While Not parser.EndOfData
Try
Dim columns As String() = parser.ReadFields()
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Catch ex As MalformedLineException
' Handle the invalid formatting error
End Try
End While
End Using
回答by John Bustos
I would break it up into a List(of string())- Each row being a new entry in the list.
我会将它分解为List(of string())- 每行都是列表中的一个新条目。
Then loop through the list and look at Value(0).
If Value(0) = MyValue, then Open = Value(1)
然后遍历列表并查看 Value(0)。
If Value(0) = MyValue, then Open = Value(1)
回答by Tim Schmelter
You can use String.Splitand this linq query:
您可以使用String.Split这个 linq 查询:
Dim Year As Int32 = 2012
Dim Month As Int32 = 10
Dim searchMonth = New Date(Year, Month, 1)
Dim lines = strBuffer.Split({Environment.NewLine}, StringSplitOptions.None)
Dim dt As Date
Dim open As Double
Dim opens = From line In lines
Let tokens = line.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Where Date.TryParse(tokens(0), dt) AndAlso dt.Date = searchMonth AndAlso Double.TryParse(tokens(1), open)
If opens.Any() Then
open = Double.Parse(opens.First().tokens(1))
End If

