15
\$\begingroup\$

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.
  • The shortest answer wins.

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

33 Answers 33

0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

PHP 65

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

Inspired from Kevin Cruijssen's java example.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$

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.