user19100232
user19100232

Reputation:

How to remove nth character in string?

I there any way to drop a character by its index from the string? For instance, drop every second letter from these words:

name <- c("Jackkk","Markkk","Jayyy")

Upvotes: 3

Views: 528

Answers (2)

jpsmith
jpsmith

Reputation: 17240

A non-regex, less elegant approach that is amenable to any position could be:

remove_n <- 2 #position to remove

unlist(lapply(strsplit(name, ""), function(x)
  paste(x[-remove_n], collapse = "")))

# [1] "Jckkk" "Mrkkk" "Jyyy"

# Other positions
remove_n <- 3
# [1] "Jakkk" "Makkk" "Jayy" 
remove_n <- 1
# [1] "ackkk" "arkkk" "ayyy" 

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 173858

You can use sub:

sub('(^.).(.*$)', '\\1\\2', name)
#> [1] "Jckkk" "Mrkkk" "Jyyy" 

Upvotes: 4

Related Questions