开发者

Split a string into 2 different substrings vb.net

I'm trying to split a string into 2 subs. The first contains the first 236 (0 to 235) chars and the second one from 237 to the end of the string.

firststr = str.Substring(0, 235)
secondstr = str.Substring(235, strLength)  'strLength is the total length of the string

strLength is generating error : Index and开发者_JAVA技巧 length must refer to a location within the string. Parameter name: length

Any help?


You need something like this:

secondstr = str.Substring(235, strLength - 235)

Because strLength is the length of the entire string, and you're starting at position 235, you're going past the end of the string.


The 2nd argument is how many charaters you need and not what the end position is. Try something like: secondstr = str.Substring(235, strLength-235) (perhaps you also need -1)


Normally data the second argument would be the length of the substring you want, in this case strLength-236. I don't know vb.net but in C# you do not need to specify the second variable strLength for secondstr when using substring because the default goes to the end of the string.

[edit] - fixed


If you just want to go to the end of a string then you can leave off the length parameter when using the Substring method. The default is to go to the end of the string.

secondstr = str.Substring(236)

will get the job done for you.


From what I see, your variable strLength has a value that's outside the boundaries of the string str.


I note noone picked up the other error in your code as described.

The second argument to Substring is the length returned, so firstStr contains the same as Left(str, 235), i.e. it contains 235 characters as you've written it, not 236.

For completeness, here's a VB solution to your query:

firststr = Left(str, 236)
secondstr = Mid(str, 237)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜