Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Haskell, how can I replace an ASCII character sub-string in a ByteString?

In Haskell, how can I replace an ASCII character sub-string in a ByteString? How can I use function replace in Data.ByteString.Search using character strings as arguments? Are there other ways to perform sub-string replacement in a ByteString? For example, would it make sense to convert the ByteString to a String, perform the string substitution using the String, and then convert the result back to a ByteString?

like image 930
Derek Mahar Avatar asked Feb 24 '14 14:02

Derek Mahar


2 Answers

The string must be converted into a ByteString using pack.

If the string is a string literal, you can use the OverloadedStrings extension. This will convert automatically the string literal into a ByteString.

like image 104
tofcoder Avatar answered Nov 15 '22 07:11

tofcoder


Example to illustrate Teetoo's answer:

Prelude> :module + Data.ByteString.Char8 Data.ByteString.Search
Prelude Data.ByteString.Char8 Data.ByteString.Search> replace (pack "World") (pack "Derek") (pack "Hello, World!")
"Hello, Derek!"
Prelude Data.ByteString.Char8 Data.ByteString.Search>
like image 43
Derek Mahar Avatar answered Nov 15 '22 07:11

Derek Mahar