check if string in r ends with another string

Check If a String in R ends with Another String

In this tutorial, we will look at how to check whether a string in R ends with a specific string (or character) or not with the help of examples.

How to check if a string in R ends with a specific string?

From the R version 3.3.0, you can use the built-in endsWith() function to check whether a string ends with a particular string or not.

Pass the string and the ending pattern string as arguments to the endsWith() function. The following is the syntax –

# check if string str ends with the string pattern
endsWith(str, pattern)

It returns TRUE if the string str ends with the string pattern.

Examples

Let’s now look at some examples of using the above syntax.

Check if a string ends with a particular character in R

Here, we will create a sample string and check whether it ends with the character “e” or not.

# create a string
s <- "Avengers Endgame"
# check if s ends with "e"
print(endsWith(s, "e"))

Output:

[1] TRUE

We get TRUE as the output, because the string “Avengers Endgame” does end with the letter “e”.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Note that the endsWith() function performs a case-sensitive match. For example, let’s check whether the string “Avengers Endgame” ends with the letter “E”.

# create a string
s <- "Avengers Endgame"
# check if s ends with "E"
print(endsWith(s, "E"))

Output:

[1] FALSE

We get FALSE as the output.

Check if a string ends with a particular string in R

You can also use the endsWith() function to check if the string ends 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 ends with "go"
print(endsWith(s, "go"))

Output:

[1] TRUE

Here, we check if the string “mango” ends with the string “go”. We get TRUE as the output because “mango” does, in fact, end with the string “go”.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top