We can extract n
characters from a given string according to our need.
In R, we can use the str_sub()
function of the stringr
package to extract n
characters from a string.
Example 1: R Program to Extract n Characters From a String
library("stringr")
string1 <- "codemy"
# extract first three characters
str_sub(string1, 1, 3) # prints "Pro"
# extract characters from 4th index to 7th index
str_sub(string1, 4, 7) # prints "gram"
Output
[1] "Pro" [2] "gram"
In the above example, we have used the str_sub()
function of the stringr
package to extract n
characters from a string.
str_sub(string1, 1, 3)
- prints all characters of string1 from 1st position to 3rd positionstr_sub(string1, 4, 7)
- prints all characters of string1 from 4th position to 7th position
Example 2: Extract n Characters From Last in R
library("stringr")
string1 <- "codemy"
# extract last three characters
str_sub(string1, -3, -1)
Output: [1] "miz"
In the above example, we have used the negative index to extract characters from the last of a string1.
Here, str_sub(string1, -3, -1)
extracts all characters of string1 from 3rd last position -3 to last position -1.