将字符串的子字符串放入数组 [英] Getting substring of string into an array

查看:96
本文介绍了将字符串的子字符串放入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,
我有一个字段,其中包含"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.


拆分没问题!

对Prera​​k正确答案的一个小改进.可以允许更宽松的输入格式:
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".

—SA


And, by the way, get rid of all those immediate constants (hard-coded), like "ListValues".

—SA


您也可以使用以上答案.
仍然要使用相同的一个.
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屋!

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