R nchar() Function - Get Number of Characters
The R nchar() function is used to count the number of characters in a string.
nchar() can handle multi-byte characters such as Chinese, and is one of the most basic functions in string processing.
The syntax of the nchar() function is as follows:
nchar(x, type = "chars")
Parameter description:
xInput string vector.
typeCounting type: "chars" (number of characters), "bytes" (number of bytes), "width" (display width).
Example
# English and Chinese
text_en <- "Hello EXAMPLE"
text_cn <- "Hello World"
print(paste("English:", nchar(text_en)))
print(paste("Chinese:", nchar(text_cn)))
# Number of characters in a vector
words <- c("R", "Python", "JavaScript", "Go")
print("Number of characters per language:")
print(nchar(words))
# Check the difference between byte count and character count
text <- "Hello World"
print(paste("Number of characters:", nchar(text, type = "chars")))
print(paste("Number of bytes:", nchar(text, type = "bytes")))
text_en <- "Hello EXAMPLE"
text_cn <- "Hello World"
print(paste("English:", nchar(text_en)))
print(paste("Chinese:", nchar(text_cn)))
# Number of characters in a vector
words <- c("R", "Python", "JavaScript", "Go")
print("Number of characters per language:")
print(nchar(words))
# Check the difference between byte count and character count
text <- "Hello World"
print(paste("Number of characters:", nchar(text, type = "chars")))
print(paste("Number of bytes:", nchar(text, type = "bytes")))
Executing the above code produces the following output:
[1] "英文: 12" [1] "中文: 4" [1] "各语言的字符数:" [1] 1 6 10 2 [1] "字符数: 8" [1] "字节数: 13"
nchar() combined with substr() can implement string truncation:
Example
# Truncate overlong strings and add an ellipsis
texts <- c("This is a very long description text that needs to be truncated",
"short text")
truncate <- function(x, max_len = 10) {
ifelse(nchar(x) > max_len,
paste0(substr(x, 1, max_len), "..."),
x)
}
print("Truncation result:")
print(truncate(texts, max_len = 8))
texts <- c("This is a very long description text that needs to be truncated",
"short text")
truncate <- function(x, max_len = 10) {
ifelse(nchar(x) > max_len,
paste0(substr(x, 1, max_len), "..."),
x)
}
print("Truncation result:")
print(truncate(texts, max_len = 8))
Executing the above code produces the following output:
[1] "截断结果:" [1] "这是一个很长的描..." "短文本"Other extensions
R Language Examples