Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of dots in character string with str_count?

Tags:

r

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)
like image 961
HansDieter Avatar asked Dec 19 '25 22:12

HansDieter


1 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, '.')
like image 102
sindri_baldur Avatar answered Dec 21 '25 11:12

sindri_baldur