I have the following string "not really//"
and I want to write a function that replaces every two slashes "//"
with two dots ".."
I thought about using map, but then I would iterate through characters and can't know if a slash is going to be followed by another or not. Any clue how this can be done? (without regex)
You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).
First, you set the edge condition "replaceO [] = []" . If the list is empty, there is nothing to replace, returning an empty list. If the head is equal to 'O', it will replace it with 'X'. and apply the replaceO function to the rest of the string.
We can use the replace :: Text -> Text -> Text -> Text
function of the Data.Text
function. For example:
Prelude Data.Text> replace "//" ".." "not really//"
"not really.."
Here we work however on Text
s. If that is a problem, we can also use pack :: String -> Text
and unpack :: Text -> String
to convert between String
and Text
. So we can define a function with:
{-# LANGUAGE OverloadedStrings #-}
import Data.Text(pack, unpack, replace)
replacedoubleslash :: String -> String
replacedoubleslash = unpack . replace "//" ".." . pack
But usually for efficient string processing - both in terms of speed and memory - using Text
is better than working with String
s.
Explicit recursion looks fine here:
replace :: String -> String
replace ('/':'/':xs) = '.' : '.' : replace xs
replace (x:xs) = x : replace xs
replace "" = ""
This does not scale to long patterns, but for replacing "//" it should work fine.
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