nchar()

nchar(x, type = "chars", keepNA = FALSE)
Returns: integer · Updated March 13, 2026 · String Functions
string base length

The nchar() function returns the length of a character string. It can measure length in characters, bytes, or display width (useful for non-ASCII text). This function is essential for string validation, padding, and text processing workflows.

Syntax

nchar(x, type = "chars", keepNA = FALSE)

Parameters

ParameterTypeDefaultDescription
xcharacterA character vector or object coercible to character
typecharacter”chars”Measurement type: “chars” (characters), “bytes” (bytes), “width” (display width)
keepNAlogicalFALSEIf TRUE, NA strings return NA instead of being treated as NA

Examples

Basic character counting

# Simple string length
nchar("hello")
# [1] 5

# Vector of strings
nchar(c("a", "ab", "abc"))
# [1] 1 2 3

Counting different types

# Characters vs bytes for Unicode
text <- "héllo"
nchar(text, type = "chars")
# [1] 5

nchar(text, type = "bytes")
# [1] 6 (UTF-8 encoding uses 2 bytes for é)

# Display width (useful for formatting)
nchar("日本語", type = "width")
# [1] 6 (each CJK character has width 2)

Handling NA values

# Default: NA becomes NA_integer_
nchar(c("text", NA, "more"))
# [1]  4 NA  4

# keepNA = TRUE: NA strings return NA
nchar(c("text", NA, "more"), keepNA = TRUE)
# [1]  4 NA  4

# Empty string returns 0
nchar("")
# [1] 0

Common Patterns

String validation

# Filter strings of specific length
words <- c("cat", "elephant", "hi", "giraffe")
words[nchar(words) > 3]
# [1] "elephant" "giraffe"

# Check if string exceeds maximum length
truncate <- function(x, max_len) {
  ifelse(nchar(x) > max_len, paste0(substr(x, 1, max_len), "..."), x)
}
truncate("This is a long string", 10)
# [1] "This is a ..."

Padding strings to uniform width

# Pad strings to equal length for display
pad_strings <- function(vec, width = 10) {
  sprintf("%-*s", width, vec)
}
pad_strings(c("a", "abc", "abcdef"))
# [1] "a         " "abc        " "abcdef    "

See Also