In this tutorial, we will look at how to check whether a string in R starts with a specific string (or character) or not with the help of examples.
How to check if a string in R begins with a specific string?
From the R version 3.3.0, you can use the built-in startsWith()
function to check whether a string starts with a particular string or not.
Pass the string and the starting pattern string as arguments to the startsWith()
function. The following is the syntax –
# check if string str starts with the string pattern startsWith(str, pattern)
It returns TRUE
if the string str
starts with the string pattern
.
Examples
Let’s now look at some examples of using the above syntax.
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
Check if a string starts with a particular character in R
Here, we will create a sample string and check whether it begins with the character “A” or not.
# create a string s <- "Avengers Endgame" # check if s starts with "A" print(startsWith(s, "A"))
Output:
[1] TRUE
We get TRUE
as the output, because the string “Avengers Endgame” does start with the letter “A”.
Note that the startsWith()
function performs a case-sensitive match. For example, let’s check whether the string “Avengers Endgame” starts with the letter “A”.
# create a string s <- "Avengers Endgame" # check if s starts with "a" print(startsWith(s, "a"))
Output:
[1] FALSE
We get FALSE
as the output.
Check if a string starts with a particular string in R
You can also use the startsWith()
function to check if the string begins with a particular string (with more than one character) or not.
Let’s look at an example.
# create a string s <- "mango" # check if s starts with "man" print(startsWith(s, "man"))
Output:
[1] TRUE
Here, we check if the string “mango” starts with the string “man”. We get TRUE
as the output because “mango” does, in fact, start with the string “man”.
You might also be interested in –
- R – Remove Whitespaces From String
- Compare Two Strings in R (With Examples)
- Convert Numeric Type to Character Type in R
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.