% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sub.R
\name{str_sub}
\alias{str_sub}
\alias{str_sub<-}
\alias{str_sub_all}
\title{Get and set substrings using their positions}
\usage{
str_sub(string, start = 1L, end = -1L)

str_sub(string, start = 1L, end = -1L, omit_na = FALSE) <- value

str_sub_all(string, start = 1L, end = -1L)
}
\arguments{
\item{string}{Input vector. Either a character vector, or something
coercible to one.}

\item{start, end}{A pair of integer vectors defining the range of characters
to extract (inclusive).

Alternatively, instead of a pair of vectors, you can pass a matrix to
\code{start}. The matrix should have two columns, either labelled \code{start}
and \code{end}, or \code{start} and \code{length}.}

\item{omit_na}{Single logical value. If \code{TRUE}, missing values in any of the
arguments provided will result in an unchanged input.}

\item{value}{replacement string}
}
\value{
\itemize{
\item \code{str_sub()}: A character vector the same length as \code{string}/\code{start}/\code{end}.
\item \code{str_sub_all()}: A list the same length as \code{string}. Each element is
a character vector the same length as \code{start}/\code{end}.
}
}
\description{
\code{str_sub()} extracts or replaces the elements at a single position in each
string. \code{str_sub_all()} allows you to extract strings at multiple elements
in every string.
}
\examples{
hw <- "Hadley Wickham"

str_sub(hw, 1, 6)
str_sub(hw, end = 6)
str_sub(hw, 8, 14)
str_sub(hw, 8)

# Negative indices index from end of string
str_sub(hw, -1)
str_sub(hw, -7)
str_sub(hw, end = -7)

# str_sub() is vectorised by both string and position
str_sub(hw, c(1, 8), c(6, 14))

# if you want to extract multiple positions from multiple strings,
# use str_sub_all()
x <- c("abcde", "ghifgh")
str_sub(x, c(1, 2), c(2, 4))
str_sub_all(x, start = c(1, 2), end = c(2, 4))

# Alternatively, you can pass in a two column matrix, as in the
# output from str_locate_all
pos <- str_locate_all(hw, "[aeio]")[[1]]
pos
str_sub(hw, pos)

# You can also use `str_sub()` to modify strings:
x <- "BBCDEF"
str_sub(x, 1, 1) <- "A"; x
str_sub(x, -1, -1) <- "K"; x
str_sub(x, -2, -2) <- "GHIJ"; x
str_sub(x, 2, -2) <- ""; x
}
\seealso{
The underlying implementation in \code{\link[stringi:stri_sub]{stringi::stri_sub()}}
}
