Hi.
I am tring to duplicate the functionality of the R
package stringr
in Julia
so that I prepare a cheatsheet for string manipulation in Julia
. Particularly, I am thinking of how to achieve str_sub()
's output in Julia
. Here is the example they are using in their stringr cheatsheet for str_sub()
:
> fruit <- c"apple", "banana", "pear", "pinapple")
> str_sub(fruit, 1, 3) <- "str"
> fruit
[1] "strle" "strana" "strr" "strapple"
>
So,
a) I was wondering whether there is an even more succinct way of doing what the above R
line of code does than the following:
julia> fruit = ["apple", "banana", "pear", "pinapple"]
julia> replace.(fruit, first.(fruit,3) .=> "str")
4-element Vector{String}:
"strle"
"strana"
"strr"
"strapple"
and
b) whether, in case we want to replace a substring from the middlle of the initial string we could use something better than the following (since the first()
would not be able to return anything in the middle of the string (?)):
julia> replace.(fruit, SubString.(fruit, Ref(3:4)) .=> "AA")
4-element Vector{String}:
"apAAe"
"baAAAA"
"peAA"
"piAApple"
Using stringr
âs functionality in R
you could achieve that with:
> str_sub(fruit, 3, 4) <- "str"
I know that stringr
is not part of base R
and it is not fair to use Base Julia
for achieving elegantly the same thing that an R
package does. However, I would be happy if I got some relevant feedback for possible alternative ways of achieving these things.
PS: Notice that if some string has a length less than the index I declare within Ref()
I get an Error
in Julia
. In R
, str_sub()
silently succeeds by doing the replacement anyway; So:
julia> replace.(fruit, SubString.(fruit, Ref(3:5)) .=> "AA")
ERROR: BoundsError: attempt to access 4-codeunit String at index [3:5]
In R
, however, it silently makes adjustments so that the replacement string replaces the last two characters for âpearâ and adds one more.
> str_sub(fruit, 3, 5) <- "str"
> fruit
[1] "apstr" "bastra" **"pestr"** "pistrple"
Thanks!