我想通过为每个字符分配不同的值来使用字符串进行一些二维行走。我计划“弹出”字符串的第一个字符,使用它,然后对字符串的其余部分重复。
我怎样才能实现这样的目标?
x <- 'hello stackoverflow'
我希望能够做这样的事情:
a <- x.pop[1]
print(a)
'h'
print(x)
'ello stackoverflow'
最佳答案
参见?substring
.
x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"
<小时/>
拥有一个既返回值又具有更新存储在 x
中的数据的副作用的 pop
方法的想法很大程度上是面向对象的概念编程。因此,我们可以创建一个 reference class ,而不是定义一个 pop
函数来操作字符向量。使用 pop
方法。
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 stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
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"
关于string - 获取和删除字符串的第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7723549/