Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count all occurrences of a char within a string

Tags:

scala

Does Scala have a native way to count all occurrences of a character in a string?

If so, how do I do it?

If not, do I need to use Java? If so, how do I do that?

Thanks!

like image 722
bonum_cete Avatar asked Oct 26 '11 21:10

bonum_cete


People also ask

How do you count a string occurrence in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count all the letters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .

How do you count occurrences of a character in a string in SQL?

In SQL Server: SELECT LEN(REPLACE(myColumn, 'N', '')) FROM ... Just be aware that if there are more than "N" or "Y" in the string then this could be inaccurate.


2 Answers

"hello".count(_ == 'l') // returns 2 
like image 112
Jean-Philippe Pellet Avatar answered Oct 09 '22 22:10

Jean-Philippe Pellet


i don't use Scala or even java but google search for "Scala string" brought me to here

which contains :

def count (p: (Char) ⇒ Boolean): Int Counts the number of elements in the string which satisfy a predicate. p the predicate used to test elements. returns the number of elements satisfying the predicate p. Definition Classes TraversableOnce → GenTraversableOnce 

Seems pretty straight forward but i dont use Scala so don't know the syntax of calling a member function. May be more overhead than needed this way because it looks like it can search for a sequence of characters. read on a different result page a string can be changed into a sequence of characters and you can probably easily loop through them and increase a counter.

like image 25
Joe McGrath Avatar answered Oct 09 '22 22:10

Joe McGrath