str_length

The function stringr::str_length() allows you to determine the length of a string. This will give you the number of characters each string has.

Tidyverse reference page

str_length

First we’ll count the number of characters in one string (a scalar).

stringr::str_length("abc")
[1] 3

Next we can count the number of characters within each string of a vector.

#Create a vector of strings
vec <- c("abc", "defghijk", "lmnopqrstuvwxyz")
#Count with a vector
stringr::str_length(vec)
[1]  3  8 15

White spaces

What about counting white spaces such as spaces (" "), tabs (\t), and new spaces (\n)?

#Create a vector of strings
vec <- c("gataac", "gat aac", "gat\taac", "gat\naac")

View the strings with stringr::str_view().

#View the strings
stringr::str_view(vec)
[1] │ gataac
[2] │ gat aac
[3] │ gat{\t}aac
[4] │ gat
    │ aac

Count the characters in the strings.

#Count characters of strings
stringr::str_length(vec)
[1] 6 7 7 7

You’ll notice that these three white spaces count as 1 character.