user2100721
user2100721

Reputation: 3597

Available function for deletion of character from certain positions of a string

I am looking for a function which performs delete operation on a string based on the position.

For example, given string is like that

string1 <- "hello stackoverflow"

Suppose, I want to delete 4th,10th and 18th positions.

Preferred Output

"helo stakoverflw"

I am not sure about the existence of such function.

Upvotes: 5

Views: 138

Answers (1)

Chase Grimm
Chase Grimm

Reputation: 425

This worked for me.

string1 <- "hello stackoverflow"
paste((strsplit(string1, "")[[1]])[-c(4,10,18)],collapse="")
[1] "helo stakoverflw"

I used strsplit to split the string into a vector of characters, and then pasted only the desired characters back together into a string.

You could also write a function that does this:

delChar <- function(x,eliminate){
  paste((strsplit(x,"")[[1]])[-eliminate],collapse = "")
}

delChar(string1,c(4,10,18))
[1] "helo stakoverflw"

Upvotes: 3

Related Questions