count_separators

How can I count the separator characters in a string?

You have a string, which you are splitting. For example:

You want to split this string at each comma. But you also want to know how many commas were in the string.

Why you can’t use split

Split will drop any null fields left at the end of the string. For example, if you used the following code:

You’d get the following output:

But the answers you would want are 10 fields (so 9 commas) for the first string, and 6 fields (5 commas) for the second string.

Solution 1

There are a number of solutions to this problem.

The first uses the ‘tr’ operator of regular expressions:

This gives you the following output:

The ‘tr’ operator returns the number of characters replaced or deleted. So in this case it gives you the number of commas in the string.

Solution 2

The second solution is a little more readable:

This gives you the correct output, as follows:

The ‘g’ modifier of the regular expression searches globally. That is it matches each occurances of the pattern in the string in turn. In this example we simply increment a counter each time a comma is matched.

See also

Scroll to Top