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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7723549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:14:08  来源:igfitidea点击:

Getting and removing the first character of a string

stringr

提问by pedrosaurio

I would like to do some 2-dimensional walks using strings of characters by assigning different values to each character. I was planning to 'pop' the first character of a string, use it, and repeat for the rest of the string.

我想通过为每个字符分配不同的值来使用字符串进行一些二维遍历。我打算“弹出”字符串的第一个字符,使用它,然后对字符串的其余部分重复。

How can I achieve something like this?

我怎样才能实现这样的目标?

x <- 'hello stackoverflow'

I'd like to be able to do something like this:

我希望能够做这样的事情:

a <- x.pop[1]

print(a)

'h'
print(x)

'ello stackoverflow'

回答by Richie Cotton

See ?substring.

?substring

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


The idea of having a popmethod that both returns a value and has a side effect of updating the data stored in xis very much a concept from object-oriented programming. So rather than defining a popfunction to operate on character vectors, we can make a reference classwith a popmethod.

有一个pop方法既返回一个值又具有更新存储的数据的副作用的想法在x很大程度上是面向对象编程的一个概念。因此,与其定义一个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"

回答by Tony Ladson

There is also str_subfrom the stringr package

还有str_sub来自stringr包

x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"

回答by bartektartanus

Use this function from stringipackage

stringi包中使用此功能

> x <- 'hello stackoverflow'
> stri_sub(x,2)
[1] "ello stackoverflow"

回答by Rich Scriven

substringis definitely best, but here's one strsplitalternative, since I haven't seen one yet.

substring绝对是最好的,但这是另一种strsplit选择,因为我还没有见过。

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

或等效地

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can pastethe rest of the string back together.

您可以paste将其余的字符串重新组合在一起。

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

回答by jon

removing first characters:

删除第一个字符:

x <- 'hello stackoverflow'
substring(x, 2, nchar(x))

Idea is select all characters starting from 2 to number of characters in x. This is important when you have unequal number of characters in word or phrase.

想法是选择从 2 开始的所有字符到 x 中的字符数。当单词或短语中的字符数不等时,这一点很重要。

Selecting the first letter is trivial as previous answers:

选择第一个字母与以前的答案一样微不足道:

substring(x,1,1)

回答by lmo

Another alternative is to use capturing sub-expressions with the regular expression functions regmatchesand regexec.

另一种选择是使用正则表达式函数regmatches和捕获子表达式regexec

# the original example
x <- 'hello stackoverflow'

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))

This returns the entire string, the first character, and the "popped" result in a list of length 1.

这将返回整个字符串、第一个字符和长度为 1 的列表中的“弹出”结果。

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). That is, it contains the super set of the desired elements as well as the full string.

这相当于list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x)))). 也就是说,它包含所需元素的超集以及完整的字符串。



Adding sapplywill allow this method to work for a character vector of length > 1.

添加sapply将允许此方法适用于长度 > 1 的字符向量。

# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')

# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))

This returns a list with the matched full string as the first element and the matching subexpressions captured by ()as the following elements. So in the regular expression '(^.)(.*)', (^.)matches the first character and (.*)matches the remaining characters.

这将返回一个列表,其中匹配的完整字符串作为第一个元素,匹配的子表达式被捕获()为以下元素。所以在正则表达式中'(^.)(.*)'(^.)匹配第一个字符并(.*)匹配剩余的字符。

myStrings
[[1]]
[1] "hello stackoverflow" "h"                   "ello stackoverflow" 

[[2]]
[1] "right back" "r"          "ight back" 

[[3]]
[1] "at yah" "a"      "t yah" 

Now, we can use the trusty sapply+ [method to pull out the desired substrings.

现在,我们可以使用 trusty sapply+[方法来提取所需的子字符串。

myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back"          "t yah"