How to find the “real” number of characters in a Unicode string in R

假装没事ソ 提交于 2019-12-09 19:12:11

问题


I know how to find the length of a not Unicode string in R.

nchar("ABC")

(thanks everyone who answered the question here: How to find the length of a string in R? ).

But what about Unicode strings?

How to find the length of a string (number of characters in a string) in a Unicode strings? How do I find the length (in bytes) and the number of characters (runes, symbols) in a Unicode string in R?


回答1:


You can use nchar for the number of characters and for the number of bytes:

nchar("bi\u00dfchen", type="chars")
#[1] 7
nchar("bi\u00dfchen", type="bytes")
#[1] 8

Indeed, in the help, you can find details about how to compute the string size:

The ‘size’ of a character string can be measured in one of three ways (corresponding to the type argument):
bytes
The number of bytes needed to store the string (plus in C a final terminator which is not counted). chars
The number of human-readable characters.
width
The number of columns cat will use to print the string in a monospaced font. The same as chars if this cannot be calculated.

If you want to know the number of "symbols" inside the string that may (or may not) contain unicode (i.e. without interpreting the unicode symbol), you can use function stri_escape_unicode from package stringi:

library(stringi)
nchar(stri_escape_unicode("bi\u00dfchen")) # same as stri_length(stri_escape_unicode("bi\u00dfchen"))
# [1] 12


来源:https://stackoverflow.com/questions/42481827/how-to-find-the-real-number-of-characters-in-a-unicode-string-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!