Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting count of occurrences for X in string

Tags:

julia

Im looking for a function like Pythons

"foobar, bar, foo".count("foo")

Could not find any functions that seemed able to do this, in a obvious way. Looking for a single function or something that is not completely overkill.

like image 950
Cruor Avatar asked Jun 03 '14 11:06

Cruor


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 the number of occurrences of an element in a string?

count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

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

In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.

How do you count the occurrences of a word in a string in Python?

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


2 Answers

Julia-1.0 update:

For single-character count within a string (in general, any single-item count within an iterable), one can use Julia's count function:

julia> count(i->(i=='f'), "foobar, bar, foo")
2

(The first argument is a predicate that returns a ::Bool).

For the given example, the following one-liner should do:

julia> length(collect(eachmatch(r"foo", "bar foo baz foo")))
2

Julia-1.7 update:

Starting with Julia-1.7 Base.Fix2 can be used, through ==('f') below, as to shorten and sweeten the syntax:

julia> count(==('f'), "foobar, bar, foo")
2
like image 81
cnaak Avatar answered Oct 21 '22 14:10

cnaak


Adding an answer to this which allows for interpolation:

julia> a = ", , ,";
julia> b = ",";
julia> length(collect(eachmatch(Regex(b), a)))
3

Actually, this solution breaks for some simple cases due to use of Regex. Instead one might find this useful:

"""
count_flags(s::String, flag::String)

counts the number of flags `flag` in string `s`.
"""
function count_flags(s::String, flag::String)
counter = 0
for i in 1:length(s)
  if occursin(flag, s)
    s = replace(s, flag=> "", count=1)
    counter+=1
  else
    break
  end
end
return counter
end
like image 32
Charles Avatar answered Oct 21 '22 13:10

Charles