R nchar() Function - Getting the Number of Characters
The R nchar() function is used to count the number of characters in a string.
nchar() can handle multibyte 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:
-
x The input vector of strings.
-
type Count type: "chars" (number of characters), "bytes" (number of bytes), "width" (display width).
Example
English and Chinese
text_en
<-
"Hello RUNOOB"
text_cn
<-
"Ni Hao Shi Jie"
(
paste
(
"English:"
,
nchar
(
text_en
)
)
)
(
paste
(
"Chinese:"
,
nchar
(
text_cn
)
)
)
Number of characters in a vector
words
<-
c
(
"R"
,
"Python"
,
"JavaScript"
,
"Go"
)
(
"Number of characters in each language:"
)
(
nchar
(
words
)
)
Check the difference between byte count and character count
text
<-
"Hello World"
(
paste
(
"Character count:"
,
nchar
(
text
, type
=
"chars"
)
)
)
(
paste
(
"Byte count:"
,
nchar
(
text
, type
=
"bytes"
)
)
)
The output of the code above is:
[1] "英文: 12"
[1] "中文: 4"
[1] "各语言的字符数:"
[1] 1 6 10 2
[1] "字符数: 8"
[1] "字节数: 13"
nchar() combined with substr() can achieve string truncation:
Example
Truncate overly long 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
)
}
(
"Truncated result:"
)
(
truncate
(
texts, max_len
=
8
)
)
The output of the code above is:
[1] "截断结果:"
[1] "这是一个很长的描..." "短文本"
R Language Examples