Search code examples
pythonrstringstartswithends-with

Does R have function startswith or endswith like python?


> startsWith('abc', 'a')
[1] TRUE
> startsWith('abc', 'c')
[1] FALSE

> endsWith('abc', 'a')
[1] FALSE  
> endsWith('abc', 'c')
[1] TRUE

Solution

  • Not inbuilt like that.

    Options include grepl and substr.

    x <- 'ABCDE'
    grepl('^AB', x) # starts with AB?
    grepl('DE$', x) # ends with DE?
    substr(x, 1, 2) == 'AB'
    substr('ABCDE', nchar(x)-1, nchar(x)) == 'DE'