且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取和删除字符串的第一个字符

更新时间:2022-02-06 16:26:30

参见 ?substring.

x <- 'hello ***'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello ***"

拥有一个 pop 方法的想法,它既返回一个值又具有更新存储在 x 中的数据的副作用,这在很大程度上是一个面向对象的概念编程.因此,与其定义一个 pop 函数来操作字符向量,不如创建一个 引用类 使用 pop 方法.


The idea of having a pop method that both returns a value and has a side effect of updating the data stored in x is very much a concept from object-oriented programming. So rather than defining a pop function to operate on character vectors, we can make a reference class with a pop method.

PopStringFactory <- setRefClass(
  "PopString",
  fields = list(
    x = "character"  
  ),
  methods = list(
    initialize = function(x)
    {
      x <<- x
    },
    pop = function(n = 1)
    {
      if(nchar(x) == 0)
      {
        warning("Nothing to pop.")
        return("")
      }
      first <- substring(x, 1, n)
      x <<- substring(x, n + 1)
      first
    }
  )
)

x <- PopStringFactory$new("hello ***")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello ***"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"