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
?
Asked
Active
Viewed 991 times
5

Derek Mahar
- 27,608
- 43
- 124
- 174
2 Answers
6
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
.

tofcoder
- 2,352
- 1
- 20
- 28
-
Do you mean I must first convert the string arguments to `ByteString` objects before I pass them to `replace`? How do I generate the replacement string argument (the second argument) to `replace`? The type of this argument must be an instance of `Substitution`. – Derek Mahar Feb 24 '14 at 15:03
-
2Yes, you have to convert the string arguments into `ByteString` objects, and `ByteString` is an instance of the typeclass `Substitution`, so it is suitable as the second argument of `replace`. – tofcoder Feb 24 '14 at 15:15
2
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>

Community
- 1
- 1

Derek Mahar
- 27,608
- 43
- 124
- 174