| « Factor Fun (Part 2) | An Overview Of Package Management » |
Replacing Characters In A String (Updated)
While I am working on the Factor package manager, I came across an interesting problem:
"how to replace certain characters with other characters in a string".
I have been looking at a few solutions. The first solution that I came up with was:
: url>path ( URL -- path )
"" swap
[
1string
{
{ ":" [ "-" ] }
{ "/" [ "-" ] }
[ "%" [ "-" ] }
[ "~" [ "-" ] }
[ "@" [ "-" ] }
[ ]
} case append
] each ;
After some chatting on IRC (thanks tizoc) I changed the solution to:
: url>path ( URL -- path )
[
{
{ CHAR: : [ CHAR: - ] }
{ CHAR: / [ CHAR: - ] }
{ CHAR: % [ CHAR: - ] }
{ CHAR: ~ [ CHAR: - ] }
{ CHAR: @ [ CHAR: - ] }
[ ]
} case
] map ;
In both solutions, I am transforming specific characters to 1 character, but this need not be the case. The solution im looking for will need to support transforming to multiple characters if needed.
To use the above word you would type:
"abc:/%" url>path
=> "abc---"
After talking to erg on #concatenative, I changed the code to use the
replace word in the sequences.lib vocabulary:
: url>path ( URL -- path )
":/%~@" "-----" replace ;
1 comment
{ CHAR: e CHAR: x }
{ CHAR: l CHAR: y }
} substitute .
=> "hxyyo woryd"