developer tip

문자열의 첫 번째 문자 가져 오기 및 제거

copycodes 2020. 9. 3. 20:03
반응형

문자열의 첫 번째 문자 가져 오기 및 제거


각 캐릭터에 다른 값을 할당하여 문자열을 사용하여 2 차원 산책을하고 싶습니다. 문자열의 첫 번째 문자를 '팝'하고 사용하고 나머지 문자열에 대해 반복 할 계획이었습니다.

이와 같은 것을 어떻게 얻을 수 있습니까?

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"

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"

stringi패키지 에서이 기능 사용

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

There is also str_sub from the stringr package

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

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

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

or equivalently

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

And you can paste the rest of the string back together.

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

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.

Selecting the first letter is trivial as previous answers:

substring(x,1,1)

Another alternative is to use capturing sub-expressions with the regular expression functions regmatches and 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.

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.


Adding sapply will allow this method to work for a character vector of length > 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.

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

참고URL : https://stackoverflow.com/questions/7723549/getting-and-removing-the-first-character-of-a-string

반응형