packages feed

carbonara-0.0.1: src/Data/Carbonara/String.hs

module  Data.Carbonara.String where



replaceStr :: String -> String -> String -> String
replaceStr from to s
    | null from || null s = s         -- if "from" is empty, there will be error
    | index == length strings  = s
    | otherwise = (take index s) ++ to ++ (replaceStr from to $ drop (index + l_from) s)
    where l_from  = length from
          l_to    = length to
          l_s     = length s
          strings = map (\i -> take l_from $ drop i s ) [0 .. (l_s - l_from)]
          -- | if l_from is 0, the string length will be $
          index   = length $ takeWhile (/= from) strings
-- | ghci> replaceStr "true" "TRUE" "true love true"  --> "TRUE love TRUE"
-- | ghci> replaceStr "$" "USD" "$20 $25"  --> "USD20 USD25"


replaceStrOnce :: String -> String -> String -> String
replaceStrOnce from to s
    | null from || null s = s         -- if "from" is empty, there will be error
    | index == length strings = s
    | otherwise = concat [ take index s, to, drop (index + l_from) s] 
    where l_from  = length from
          l_to    = length to
          l_s     = length s
          strings = map (\i -> take l_from $ drop i s ) [0 .. (l_s - l_from)]
          -- | if l_from is 0, the string length will be larger 
          index   = length $ takeWhile (/= from) strings          
-- | ghci> replaceStrOnce "true" "TRUE" "true love true"  --> "TRUE love true"
-- | ghci> replaceStrOnce "$" "USD" "$20 $25"  --> "USD20 $25"