The challenge involve simply toggling a string within another string.


If the toggle string is a substring of the main string, remove all instances of the toggle string from the main string; otherwise, append the toggle string at the end of the main string.


  • All string are composed of printable ASCII characters
  • The function should take two parameters: the main string and the toggle string.
  • The main string can be empty.
  • The toggle string cannot be empty.
  • The result should be a string, which can be empty.
  • The shortest answer wins.


function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now') 
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now') 
=> 'this string has 5 words'

Tests cases

'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
  • 2
    \$\begingroup\$ @KennyLau It was in the sandbox for all of 3 hours. The recommendation is 2 days. \$\endgroup\$ Commented May 20, 2016 at 13:18
  • 10
    \$\begingroup\$ The recommendation is actually 72 hours. The main page has much more visibility than the Sandbox, so more comments are guaranteed here. That said, this isn't a bad challenge, just has a few rough edges. \$\endgroup\$ Commented May 20, 2016 at 13:19
  • 2
    \$\begingroup\$ So you replace all non-overlapping instances? \$\endgroup\$
    – Suever
    Commented May 20, 2016 at 13:26
  • 1
    \$\begingroup\$ @Jakube Yes, I should limit this to letters and number I think. \$\endgroup\$
    – nobe4
    Commented May 20, 2016 at 16:20
  • 1
    \$\begingroup\$ No, I think allow nonalphanumerics: it's more challenging that way. \$\endgroup\$
    – msh210
    Commented May 22, 2016 at 7:35

33 Answers 33


Rust, 84 bytes

fn toggle(a:&str,b:&str)->String{let mut r=a.replace(b,"");if&r==a{r.push_str(b)}r}

Try it on play.rust-lang.org.


PHP 65

function f($s,$v){return($m=str_replace($v,'',$s))==$s?$s.$v:$m;}

Inspired from Kevin Cruijssen's java example.


PHP, 73 chars


Longer than the other php answer, but uninspired and fully working as a standalone in the console.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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