R Program to Trim Leading and Trailing Whitespaces

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Example 1: Remove Whitespaces in R

text1 <- "     Programiz Pro         "
 
# remove whitespaces using trimws()
print(trimws(text1))

Output

[1] "Programiz Pro"

In the above example, we have used the trimws() function to remove the leading and trailing whitespace. It doesn't remove whitespace that appears in the middle.


Example 2: Remove Leading Whitespaces in R

text1 <- "     Programiz Pro         "
 
# remove leading whitespaces using trimws()
print(trimws(text1, "l"))

Output

[1] "Programiz Pro         "

In the above example, we have passed "l" inside the trimws() function to remove the leading whitespaces in the text1 string.


Example 3: Remove Trailing Whitespaces in R

text1 <- "     Programiz Pro         "
 
# remove trailing whitespaces using trimws()
print(trimws(text1, "r"))

Output

[1] "     Programiz Pro"

In the above example, we have passed "r" inside the trimws() function to remove the trailing whitespaces in the text1 string.

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)