如何编写一个函数来计算字符串中的字符数?

问题描述 投票:0回答:3

我正在为一个班级做练习,但我陷入了僵局。说明状态:

编写一个函数,接受一串文本并计算字符数。该函数应返回“该字符串中有 xx 个字符。”

这是我到目前为止所拥有的:

w <- "I hope everyone has a good weekend"


answer <- function (nchar) {
  statement <- paste("There are", nchar, "characters in that string")
}

我已经尝试将“w”插入函数中以查看它是否有效,但我没有得到任何结果。请记住,我是 R 的新手。

我错过了什么?

r function character
3个回答
1
投票

nchar
是计算字符串中字符数的函数。如果您不想计算空格,您可以使用
gsub
将它们从字符串中删除并再次计算字符数。您可以使用以下代码:

w <- "I hope everyone has a good weekend"

answer <- function (x) { 
  statement <- paste("There are", nchar(x), "characters in that string")
  statement
}
answer(w)
#> [1] "There are 34 characters in that string"

answer2 <- function (x) { 
  statement <- paste("There are", nchar(gsub(" ", "",x))
, "characters in that string")
  statement
}
answer2(w)
#> [1] "There are 28 characters in that string"

创建于 2023-02-03 与 reprex v2.0.2


1
投票

你混淆了函数

nchar()

用你的功能输入

请看以下内容:

w<- "I hope everyone has a good weekend"

回答<- function (myInputString) { statement <- paste("There are", nchar(myInputString), "characters in that string")
返回(声明)}

请注意,您还错过了在函数末尾添加 return 以指定输出的内容。

祝你在编码之旅中好运;)


1
投票

只是为了一点乐趣 - 并让您尝试弄清楚发生了什么 - 这里有一些替代函数,它们给出与内置

nchar
相同的答案,但实际上并不使用它......

这个将它拆分成单个字符的列表,将其转换为向量,并返回长度...

nchar1 <- function(s) length(unlist(str_split(s, "")))

这个将其转换为 RAW 格式(用于对字符串进行编码的字节值的向量)并返回长度...

nchar2 <- function(s) length(charToRaw(s))

这个使用

while
循环来查看子字符串函数
substr
在哪一点返回空字符串...

nchar3 <- function(s){
  i <- 0
  while(substr(s, i+1, i+2) != ""){
    i <- i+1
    }
  return(i)
}

这个使用类似的方法来计算在得到空字符串之前我们可以删除第一个字符的次数...

nchar4 <- function(s){
  i <- 0
  while(s != ""){
    s <- sub(".", "", s)
    i <- i + 1
  }
  return(i)
}

这个可能会让你的头有点痛。它使用与上一个类似的技术,但使用

Recall
调用自身,直到它到达返回答案的点(空白字符串)。

nchar5 <- function(s, n = 0){
  if(s == "") {
    return(n)
  } else {
    Recall(sub(".", "", s), n + 1)
  }
}

nchar1("Good luck!")
[1] 10
nchar2("Good luck!")
[1] 10
nchar3("Good luck!")
[1] 10
nchar4("Good luck!")
[1] 10
nchar5("Good luck!")
[1] 10
© www.soinside.com 2019 - 2024. All rights reserved.