Substring Operation

Finding substrings are one of the most common string manipulation operations.

substr

The substr() could be used to extract, replace parts of the string.

substr('string manipulation', 3, 6) # Usage of substr function.
## [1] "ring"
s <- 'string manipulation'
substr(s, 3, 6) <- 'RING'   # Replacing strings with the substr function.
s
## [1] "stRING manipulation"

substring

The substring() functions performs the same operations on a character vector.

x <- c('abcd', 'aabcb', 'babcc', 'cabcd') # Extracting characters using the substring function   
substring(x, 2, last=4)
## [1] "bcd" "abc" "abc" "abc"
substring(x, 2, last=4) <- 'AB' # Replacing strings with the substring function.
x
## [1] "aABd"  "aABcb" "bABcc" "cABcd"

str_sub

The stringr package offers str_sub() which is a equivalent of substring(). The str_sub() function handles negative values even more robustly than the substring() function.

y <- c("string", "manipulation", "always", "fascinating")

substring(y, first=-4, last=-1) # Using the substring functions with negative indices.
## [1] "" "" "" ""
str_sub(y ,  start=-4, end=-1)  # Using the str_sub function to handle negative indices.
## [1] "ring" "tion" "ways" "ting"
str_sub(y, start=-4, end=-1) <- 'RING' # String replacement using the str_sub function.
y
## [1] "stRING"       "manipulaRING" "alRING"       "fascinaRING"