Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the elements in string

Tags:

javascript

I have a string that has comma separated values. How can I count how many elements in the string separated by comma? e.g following string has 4 elements

string = "1,2,3,4";
like image 692
Asim Zaidi Avatar asked Jun 17 '10 21:06

Asim Zaidi


People also ask

Can you count characters in a string?

count() method, and the String. length() method. You can count characters from strings, including spaces, without spaces, and the occurrence of the specific character in a string by using these methods. This tutorial discussed the methods to count characters in a string in Java.

What is count () in Python?

Conclusion: Count() is a Python built-in function that returns the number of times an object appears in a list. The count() method is one of Python's built-in functions. It returns the number of times a given value occurs in a string or a list, as the name implies.

How do you count the list of elements?

Using Len() function to Get the Number of Elements We can use the len( ) function to return the number of elements present in the list.

How do you count occurrences of a string in Python?

Python String count() The count() method returns the number of occurrences of a substring in the given string.


1 Answers

All of the answers suggesting something equivalent to myString.split(',').length could lead to incorrect results because:

"".split(',').length == 1

An empty string is not what you may want to consider a list of 1 item.

A more intuitive, yet still succinct implementation would be:

myString.split(',').filter((i) => i.length).length

This doesn't consider 0-character strings as elements in the list.

"".split(',').filter((i) => i.length).length
0

"1".split(',').filter((i) => i.length).length
1

"1,2,3".split(',').filter((i) => i.length).length
3

",,,,,".split(',').filter((i) => i.length).length
0
like image 125
0x6A75616E Avatar answered Oct 03 '22 01:10

0x6A75616E