Disclaimer: this is theoretical question with the purpose of increasing my understanding. I know that I can always use tools like a JSON library to solve the problem.
Suppose I want to create a comma separated list of values which may themselves contain comma's. These commas need to be escaped first. Assuming that I use .
as the escape character then ["a", "b,c"]
becomes a,b.,c
.
However, if one of the values originally contained a .,
sequence then we'd need to escape those before escaping the commas. So [ "a", "b.,c" ]
becomes a,b..,c
.
However, if one of the values originally contained a ..,
sequence then we'd need to escape those before escaping the commas. So [ "a", "b..,c" ]
becomes a,b...,c
.
However, if one of the values originally contained a ...,
sequence then we'd need to escape those before escaping the commas. So [ "a", "b...,c" ]
becomes a,b....,c
.
Etc...
The decoding process must perform the reversed recursion.
However, I suspect if I'm making it too hard and there is a simpler way. Is there a simpler way?
Escaping is a method that allows us to tell a computer to do something special with the text we supply or to ignore the special function of a character. To tell the computer that it should expect an escape character we use a special escape marker, we usually make use of the backslash ().
Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark (").
Thanks to @mkbeckish' comment I realized that the algorithm can be implemented as:
// encoding
text.replace(escape, escape + escape);
text.replace(delim , escape + delim);
// decoding
text.replace(escape + delim , delim);
text.replace(escape + escape, escape);
Example implementation.
It's silly that I didn't realize this myself..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With