← Back to R Course | Chapter 6: Strings | Lesson 2 of 7

nchar

nchar counts how many letters are in a piece of text, like counting the beads on a necklace. It works on a whole list of words at once too.

In this page:

  1. nchar
Syntax
r
nchar(string_or_vector)

nchar

nchar() returns the number of characters in a string, and applied to a vector of strings, it returns a vector of lengths. It's the R equivalent of a string-length function found in most languages.

This is different from length(), which for a single string returns 1 (since a string is a vector of length 1 containing one character element).

Warning: length("hello") returns 1 (it's a vector containing one string), not 5 -- use nchar() to get the character count.

Example: nchar

markup
text <- "Hello, R!"

cat(nchar(text), "\n")
cat(length(text), "\n")  # this is 1, not the character count
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using length(text) to count characters, which gives 1 for a single string; use nchar(text).
  2. Expecting nchar(NA) to be 0, when it is 2 for a logical NA and NA_integer_ for character NA.
  3. Forgetting that nchar counts characters, not bytes, unless type = "bytes" is set.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.