将字符串的子字符串放入数组 [英] Getting substring of string into an array
问题描述
你好朋友,
我有一个字段,其中包含"AA,BB,CC,DD"之类的数据.我正在尝试获取如下字符串数组中的数据
Hello friends,
I have field which holds data like ''AA,BB,CC,DD''. I''m trying to get the data in string array like following
AA
BB
CC
DD
我尝试了以下代码:
I have tried following code:
For Each row In objDS.Tables(0).Rows
Dim strListValues() As String
'GET ARRAY INDEX COUNT
Dim intCount, strPos, intStart As Integer
intCount = 0
intStart = 0
Dim strLength, strChar As String
strLength = Convert.ToString(row.Item("ListValues").ToString).Length
For strPos = 0 To (strLength - 1)
strChar = Convert.ToString(row.Item("ListValues").ToString).Chars(strPos)
Select Case (strChar)
Case ","
'GET SUBSTRING IN ARRAY
strListValues(intCount) = Convert.ToString(row.Item("ListValues").ToString).Substring(intStart, strPos)
intStart = strChar + 1
intCount = intCount + 1
End Select
Next
Next
我说
I''m getting error saying
Object reference not set to an instance of an object.
推荐答案
Split
怎么了?!
strListValues() = row.Item("ListValues").ToString.Split(",")
顺便说一句,出现的错误是因为您使用的是未初始化的strListValues
.
您需要在需要时使用strListValues(length)
或Redim
.
BTW, error you are getting is because you are using strListValues
un-initialised.
You need to use strListValues(length)
or Redim
it as and when required.
拆分没问题!
对Prerak正确答案的一个小改进.可以允许更宽松的输入格式:
Nothing''s wrong with split!
A minor improvement to the correct Answer by Prerak. Could allow a bit more relaxed input format:
strListValues[] = row.Item("ListValues").ToString().Split(
new char[] {',', ' '},
System.StringSplitOptions.RemoveEmptyEntries);
并且顺便说一下,摆脱所有那些立即数常量(硬编码),例如"ListValues
".
And, by the way, get rid of all those immediate constants (hard-coded), like "ListValues
".
您也可以使用以上答案.
仍然要使用相同的一个.
You can use above answer also.
Still you want to go with the same one use this.
Select Case (strChar)
Case ","
''GET SUBSTRING IN ARRAY
ReDim strListValues(intCount1)
strListValues(intCount) = Convert.ToString(row.Item("ListValues").ToString).Substring(intStart, strPos)
intStart = strChar + 1
intCount = intCount + 1
End Select
因为您没有初始化字符串数组的长度.
Because you did not initialize the length of string array.
这篇关于将字符串的子字符串放入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!