R Program to Replace Characters in a String

In R, we can replace any character or sequence of characters with new ones in a given string. For example,

string1 <- "Programiz" 

Here, "z" in string1 can be replaced with "ng" to make a new string "Programing".

We can use the gsub() function or the sub() function in R to replace characters in a string.


Example 1: R Program to Replace Characters Using gsub()

string1 <- "Programiz"

# replace "z" with "ng" using gsub()
gsub("z", "ng", string1) # programing

Output

[1] "Programing"

In the above example, we have used the gsub() function to replace characters in the string string1. Notice the code,

gsub("z", "ng", string1)

Here, gsub() takes three arguments

  • "z" - old character to be replaced from string1
  • "ng" - new characters to be replaced with
  • string1 - a character string

Since "z" of string1 is replaced with "ng", the function returns "Programing".


Example 2: R Program to Replace Characters Using sub()

string1 <- "Programiz.com"

# replace ".com" with ".pro" using sub()
gsub(".com", ".pro", string1)  # programiz.pro

Output

[1] "Programiz.pro"

In the above example, we have used the sub() function to replace characters in the string string1.

Here, ".com" of string1 is replaced with ".pro". So the function returns "Programiz.pro".

Note: The syntax for the sub() function is exactly the same as gsub(). You can use anyone according to your convenience.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges