Count number of dots in character string with str_count?

Viewed 622

I am trying to count the number of dots in a character string.

I have tried to use str_count but it gives me the number of letters of the string instead.

ex_str <- "This.is.a.string" 
str_count(ex_str, '.')
nchar(ex_str)
4 Answers

. is a special regex symbol, so you need to escape it:

str_count(ex_str, '\\.')
# [1] 3

Using just base R you could do:

nchar(gsub("[^.]", "", ex_str))

Using stringi:

stri_count_fixed(ex_str, '.')

Another base R solution could be:

length(grepRaw(".", ex_str, fixed = TRUE, all = TRUE))

[1] 3

You may also use the base function gregexpr:

sum(gregexpr(".", ex_str, fixed=TRUE)[[1]] > 0)
[1] 3

You can use stringr::str_count with a fixed(...) argument to avoid treating it as a regular expression:

str_count(ex_str, fixed('.'))

See the online R demo:

library(stringr)
ex_str <- "This.is.a.string" 
str_count(ex_str, fixed('.'))
## => [1] 3
Related