MYaseen208
MYaseen208

Reputation: 23898

Inserting space at specific location in a string

I want to add white space after three character in a string. I used the following code which works well. I wonder if there is any other simple way to accomplish the same task

library(stringi)
Test <- "3061660217"
paste(
    stri_sub(str = Test, from = 1, to = 3)
  , stri_sub(str = Test, from = 4)
  , sep = " "
  )

[1] "306 1660217"

Upvotes: 3

Views: 2793

Answers (1)

bird
bird

Reputation: 3294

Using basic regex and stringr:

library(stringr)
str_replace(Test, pattern = "(.{3})(.*)", replacement = "\\1 \\2")

Output:

"306 1660217"

Same method works with base R as well:

gsub(Test, pattern = "(.{3})(.*)", replacement = "\\1 \\2")

Explanation:

  1. (.{3}) - find any 3 characters
  2. (.*) - find any character 0 or more times
  3. \\1 - backreferences (.{3})
  4. \\2 - backreferences (.*)
  5. The space between \\1 and \\2 is the space you want to add

Upvotes: 7

Related Questions