Implement a program that given three strings a, b, and c, substitutes all instances of the substring b in a with c.

In other words, implement Ruby's String#gsub with strings instead of regexes (a.gsub b, c).


  • Standard loopholes apply.
  • You may not use a builtin that performs this exact task.
  • This is , shortest answer wins.

Dupe alert

Not a duplicate of this challenge.

Test case

sub("test 1 test 1 test 1", "1", "what")
  --> "test what test what test what"
  • 7
    \$\begingroup\$ This has all the typical problems of do X without Y challenges. Are splitting/joining built-ins allowed? If so, this is trivial and there's really no reason to ban sibstitution built-ins. If not, what is allowed? \$\endgroup\$ – Dennis Nov 20 '16 at 2:57
  • 1
    \$\begingroup\$ @wat You answered yes for Dennis's question about using string split/join, then said in question that they are not allowed. So they are allowed and not allowed at the same time? \$\endgroup\$ – Link Ng Nov 20 '16 at 3:18
  • 1
    \$\begingroup\$ By "join or split strings" do you mean "join or split anything"? As an example Jelly 5 bytes œṣµj⁵ does not split any strings since Jelly has no strings. \$\endgroup\$ – Jonathan Allan Nov 20 '16 at 3:19
  • \$\begingroup\$ Modifying the challenge to fit Jelly will just result in another language being pointed out that doesn't fit the wording. It's easiest just not to ban built ins. \$\endgroup\$ – trichoplax Nov 20 '16 at 3:25
  • \$\begingroup\$ @wat - lists, numbers (decimals, reals, complex) and characters. The above is achieved with a list of characters. \$\endgroup\$ – Jonathan Allan Nov 20 '16 at 4:02

JavaScript (ES6), 27 bytes


Jelly, 4 bytes


Try it online!

How it works

œṣj⁵  Main link. Arguments: x, y, z (strings)

œṣ    Split x around occurrences of y.
  j⁵  Join the resulting string array with separator z.

Haskell, 44 bytes

import Data.Lists

Argument order is c b a. Usage example: ( (.splitOn).(.).intercalate ) "ww" "ee" "aeedwwfeegeh" -> "awwdwwfwwgeh".

Just some library functions to split the input string at every b and rejoin the parts with c in-between.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.