Creates an anonymous function that returns the expected result.
The argument order is $full_string
, $substring
and then $number
.
fn($F$S$N)&iff(run&len(&str_split($F$S))>$N&str_rev(&str_replace(&str_rev($F)&str_rev($S)''$N))$F);
How does it work?
First, splits the full string by the substring, and counts the number of elements.
When splitting the string:
- If the substring isn't present, returns 1 element.
- If it is present, returns 1 extra element.
Example: &str_split("abcbdbebf", 'b') -> ["a", "c", "d", "e", "f"]
For 4 'b'
s, returns 5 elements.
If the number of elements is higher than $number
, that means there's at least $number
substrings in the full string.
The &iff()
function is just the same as a ternary operator, in C-like languages.
To remove from the end of the string, I need to reverse the string, since there isn't a way to indicate to remove from the end of the string.
However, it takes an argument that indicates how many times to replace, which means, it will replace up to $number
occurrences.
The result is returned automatically, since it is a function without a scope, just like an arrow function in JavaScript.
Ungolfed
Code-y looking:
$fn = fn($full_string, $substring, $num) => &iff(
(call &len(&str_split($full_string, $substring))) > $num,
&str_rev(
&str_replace(
&str_rev($full_string),
&str_rev($substring),
'', $num
)
),
$full_string
);
Pseudo-code looking:
Set $fn to an anonymous function ($full_string, $substring, $num)
Begin.
Set $count to the result of calling &len(Call &str_split($full_string, $substring)).
Return the result of calling &iff(
$count > $num,
Call &str_rev(
Call &str_replace(
Call &str_rev($full_string),
Call &str_rev($substring),
'', $num
)
),
$full_string
).
End.
memeowow
? What if matches overlap? \$\endgroup\$Cats do meow not memeowow, they do meow-ing.
where n=3? \$\endgroup\$n
occurrences of the substring from the input. If the input contains more than thann
occurrences of the substring, only the lastn
should be removed. If the input contains fewer thann
occurrences, it should be returned unchanged". \$\endgroup\$