R Program to Trim Leading and Trailing Whitespaces

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.

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community