Home > Software engineering >  Remove n last character from a string
Remove n last character from a string

Time:11-09

I would like to remove the third and fourth last character from as string.

Here is some sample data:

HS0202
HS0902
MV0100
SUE0300

I would need return something like this

HS02
HS02
MV00
SUE00

CodePudding user response:

Using a regex with gsub():

gsub("..(?=..$)", "", chrs, perl = TRUE)
# "HS02"  "HS02"  "MV00"  "SUE00"

CodePudding user response:

You can extract from first to fourth last characters, and paste on the final character as follows:

have <- c('HS0202', 'HS0902', 'MV0100', 'SUE0300')

want <- paste0(substring(have,1,nchar(have)-3),substring(have,nchar(have)))

CodePudding user response:

Using stringi:

library(stringi)

stri_sub_replace(x, from = -4, to = -3, value = "")

[1] "HS02"  "HS02"  "MV00"  "SUE00"

Or with stringr:

library(stringr)

str_sub(x, start = -4, end = -3) <- ""

Data

x <- c("HS0202", "HS0902", "MV0100", "SUE0300")
  • Related