R编程中查找字符串的长度——nchar()方法
R 编程语言中的 nchar() 方法用于获取字符串对象中字符的长度。
Syntax: nchar(string)
Where: String is object.
Return: Returns the length of a string.
R – 使用 nchar() 的字符串长度示例
示例 1:在 R 中查找字符串的长度
在此示例中,我们将了解如何使用 nchar() 方法获取字符串对象的长度。
R
# R program to calculate length of string
# Given String
gfg < - "Geeks For Geeks"
# Using nchar() method
answer < - nchar(gfg)
print(answer)
R
# R program to get length of Character Vectors
# by default numeric values
# are converted into characters
v1 <- c('geeks', '2', 'hello', 57)
# Displaying type of vector
typeof(v1)
nchar(v1)
R
# R program to create Character Vectors
# by default numeric values
# are converted into characters
v1 <- c(NULL, '2', 'hello', NA)
nchar(v1, keepNA = FALSE)
R
# R program to create Character Vectors
# by default numeric values
# are converted into characters
v1 <- c('', NULL, 'hello', NA)
nchar(v1, keepNA = TRUE)
输出:
[1] 15
示例 2:将 nchar 用于 R 向量
在此示例中,我们将使用 nchar() 方法获取向量的长度。
R
# R program to get length of Character Vectors
# by default numeric values
# are converted into characters
v1 <- c('geeks', '2', 'hello', 57)
# Displaying type of vector
typeof(v1)
nchar(v1)
输出:
'character'
5 1 5 2
示例 3:将 NA 值传递给 nchar()函数
nchar()函数提供了一个名为 keepNA 的可选参数,它可以在处理 NA 值时提供帮助。
R
# R program to create Character Vectors
# by default numeric values
# are converted into characters
v1 <- c(NULL, '2', 'hello', NA)
nchar(v1, keepNA = FALSE)
输出:
1 5 2
在上面的示例中,第一个元素为 NULL,然后它什么也不返回,最后一个元素 NA 返回 2,因为我们保持 keepNA = FALSE。如果我们通过keepNA = TRUE,那么看到以下输出:
R
# R program to create Character Vectors
# by default numeric values
# are converted into characters
v1 <- c('', NULL, 'hello', NA)
nchar(v1, keepNA = TRUE)
输出:
0 5