Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R nchar() Function - Getting the Number of Characters

R nchar() Function - Getting the Number of Characters

R Language Examples R Language Examples

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:

Example

English and Chinese

text_en

<-

"Hello RUNOOB"

text_cn

<-

"Ni Hao Shi Jie"

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 in each language:"

)

print

(

nchar

(

words

)

)

Check the difference between byte count and character count

text

<-

"Hello World"

print

(

paste

(

"Character count:"

,

nchar

(

text

, type

=

"chars"

)

)

)

print

(

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

)

}

print

(

"Truncated result:"

)

print

(

truncate

(

texts, max_len

=

8

)

)

The output of the code above is:

[1] "截断结果:"

[1] "这是一个很长的描..." "短文本"

R Language Examples R Language Examples