startsWith

0th

Percentile

Does String Start or End With Another String?

Determines if entries of x start or end with string (entries of) prefix or suffix respectively, where strings are recycled to common lengths.

startsWith() is equivalent to but much faster than

substring(x, 1, nchar(prefix)) == prefix
or also
grepl("^", x)
where prefix is not to contain special regular expression characters.

Keywords
utilities, character
Usage
startsWith(x, prefix) endsWith(x, suffix)
Arguments
x
vector of character string whose “starts” are considered.
prefix, suffix
character vector (often of length one).
Details

The code has an optimized branch for the most common usage in which prefix or suffix is of length one, and is further optimized in a UTF-8 or 8-byte locale if that is an ASCII string.

Value

A logical vector, of common length of x and prefix (or suffix), i.e., of the longer of the two lengths unless one of them is zero when the result is also of zero length. A shorter input is recycled to the output length.

See Also

grepl, substring; the partial string matching functions charmatch and pmatch solve a different task.

Aliases
  • endsWith
  • startsWith
Examples
library(base) startsWith(search(), "package:") # typically at least two FALSE, nowadays often three x1 <- c("Foobar", "bla bla", "something", "another", "blu", "brown", "blau bl├╝ht der Enzian")# non-ASCII x2 <- cbind( startsWith(x1, "b"), startsWith(x1, "bl"), startsWith(x1, "bla"), endsWith(x1, "n"), endsWith(x1, "an")) rownames(x2) <- x1; colnames(x2) <- c("b", "b1", "bla", "n", "an") x2
Documentation reproduced from package base, version 3.3, License: Part of R @VERSION@

Community examples

mark@niemannross.com at Jan 23, 2019 base v3.5.2

[Example files for LinkedIn Learning](https://linkedin-learning.pxf.io/rweekly_simplestringmatch) ```r haystack <- c("red", "blue", "green", "blue", "green forest") needle <- c("green", "blue", "cyan", "g") match(needle, haystack) # first position, missing value = NA needle %in% haystack # boolean startsWith(haystack, "green") endsWith(haystack, "green") ```