拆分字符串并为变量赋值 [英] Splitting a string and assigning values to variables

查看:25
本文介绍了拆分字符串并为变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拆分一个字符串并获取拆分的部分并将它们分配给变量.这适用于第一个变量,但我无法让第二个变量起作用.

I am trying to split a string and take the split parts and assign them to variables. This works fine with the first variable but I cannot get the second variable to work.

For Each columnQuarter As DataColumn In dt.Columns
            Dim s As String = columnQuarter.ColumnName
            Dim words As String() = s.Split("-")
            Dim Year As String = words(0)
            Dim Quarter As String = words(1)
            Debug.WriteLine(Year)
            Debug.WriteLine(Quarter)

在Dim Quarter As String = words(1)"行中,我收到错误代码IndexOutofRangeException 未处理.索引超出数组范围."

At line "Dim Quarter As String = words(1)" I get error code "IndexOutofRangeException was unhandled. Index was outside the bounds of the array."

ColumnName 的示例是 2012-Q1.

An example of a ColumnName would be 2012-Q1.

附加信息:

这是我用来将列添加到数据表的代码.如您所见,我的前两列不包含-".

Here is the code that I use to add my columns to my dataTable. As you can see my first two columns do not contain "-".

tickerColumn = New DataColumn("Ticker", Type.GetType("System.String"))
consistencyColumn = New DataColumn("Consistency", Type.GetType("System.Int32"))
dt.Columns.Add(tickerColumn)
dt.Columns.Add(consistencyColumn)

    With Me
        lr = Now.Year - 1901
        For i = 1 To lr
            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q4"
            dt.Columns.Add(column)

            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q3"
            dt.Columns.Add(column)

            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q2"
            dt.Columns.Add(column)

            column = New DataColumn
            column.DataType = System.Type.GetType("System.Int32")
            column.ColumnName = Now.Year - i & "-Q1"
            dt.Columns.Add(column)
        Next i
    End With

推荐答案

由于前两列没有破折号,请尝试将它们过滤掉:

Since your first two columns do NOT have the dash, try filtering them out:

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)
      Debug.WriteLine(Year)
      Debug.WriteLine(Quarter)
    End If
Next

这篇关于拆分字符串并为变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆