# Toggle a string

The challenge involve simply toggling a string within another string.

## Explanation

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.

## Rules

• 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.

## Examples

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'

• @KennyLau It was in the sandbox for all of 3 hours. The recommendation is 2 days. – Morgan Thrapp May 20 '16 at 13:18
• 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. – AdmBorkBork May 20 '16 at 13:19
• So you replace all non-overlapping instances? – Suever May 20 '16 at 13:26
• @Jakube Yes, I should limit this to letters and number I think. – nobe4 May 20 '16 at 16:20
• No, I think allow nonalphanumerics: it's more challenging that way. – msh210 May 22 '16 at 7:35

# 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.

function f($s,$v){return($m=str_replace($v,'',$s))==$s?$s.$v:$m;}  Inspired from Kevin Cruijssen's java example. # PHP, 73 chars <?$s=$argv[1];$t=$argv[2];echo!strpos($s,$t)?$s.$t:str_replace($t,'',\$s);

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