module  Data.Carbonara.String where


-- | > replaceStr "true" "TRUE" "true love true"  --> "TRUE love TRUE"
--   > replaceStr "$" "USD" "$20 $25"  --> "USD20 USD25"
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


-- | > replaceStrOnce "true" "TRUE" "true love true"  --> "TRUE love true"
--   > replaceStrOnce "$" "USD" "$20 $25"             --> "USD20 $25"
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          

-- |
test_hello :: String
test_hello = "hello"
