Gopal
Gopal

Reputation: 11982

How to count the number of space-delimited substrings in a string

Dim str as String
str = "30 40 50 60"

I want to count the number of substrings.

Expected Output: 4

(because there are 4 total values: 30, 40, 50, 60)

How can I accomplish this in VB6?

Upvotes: 1

Views: 2792

Answers (3)

Nonym
Nonym

Reputation: 6299

You could try this:

arrStr = Split(str, " ")
strCnt = UBound(arrStr) + 1
msgBox strCnt

Of course, if you've got Option Explicit set (which you should..) then declare the variables above first..

Upvotes: 5

James Mnatzaganian
James Mnatzaganian

Reputation: 1285

I agree with everything Cody stated.

If you really wanted to you could loop through the string character by character and count the number of times you find your delimiter. In your example, it is space delimited, so you would simply count the number of spaces and add 1, but as Cody stated, those are not separate values..

Are you trying to parse text here or what? Regardless, I think what you really need to do is store your data into an array. Make your life easier, not more difficult.

Upvotes: 1

Cody Gray
Cody Gray

Reputation: 244752

Your request doesn't make any sense. A string is a sequence of text. The fact that that sequence of text contains numbers separated by spaces is quite irrelevant. Your string looks like this:

30 40 50 60

There are not 4 separate values, there is only one value, shown above—a single string.

You could also view the string as containing 11 individual characters, so it could be argued that the "count" of the string would be 11, but this doesn't get you any further towards your goal.

In order to get the result that you expect, you need to split the string into multiple strings at each space, producing 4 separate strings, each containing a 2-digit numeric value.

Of course, the real question is why you're storing this value in a string in the first place. If they're numeric values, you should store them in an array (for example, an array of Integers). Then you can easily obtain the number of elements in the array using the LBound() and UBound() functions.

Upvotes: 1

Related Questions