count the elements in string

ε祈祈猫儿з 提交于 2021-02-16 09:56:09

问题


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";


回答1:


myString.split(',').length




回答2:


var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;



回答3:


First split it, and then count the items in the array. Like this:

"1,2,3,4".split(/,/).length;



回答4:


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


来源:https://stackoverflow.com/questions/3065941/count-the-elements-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!