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!
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.
In Python, you can get the length of a string str (= number of characters) with the built-in function len() .
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.
"hello".count(_ == 'l') // returns 2
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With