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

nchar

In this page:

  1. nchar

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
🔒

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.