Hey, everyone. We've decided to host a daily challenge series. We'll have a variety of challenges, ranging in difficulty and complexity. If you choose to accept the task, your goal is to write the most efficient function you can for your language. Bonus points for any features you add!
Iāll start you off with a simple, straightforward challenge. Our first one comes from user @SteadyX on CodeWars.
Your goal is to create a function that removes the first and last letters of a string. Strings with two characters or less are considered invalid. You can choose to have your function return null or simply ignore.
The fundamentals are important, it only gets more difficult from here.
Happy coding!
Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (114)
CSS
Just add the class
removeFirstAndLastLetter
to a tag, and see the first and last letter "removed" from the text šAnd as an extra, it can be stylized and animated, so you can see the letters fade out:
Ha! This one is great.
Thanks :)
JavaScript
Python
C++
C
Let people do something š
HAHAHA damn. Let me finish my code LOL.
Let's just go wild
Why not?
This is indeed wild
In JavaScript it could be 24 bytes:
I am surprised no one wrote test code. Sometimes in interviews with challenge this simple and you have access to run ruby they are expecting to see test code. Check out my ruby test code tutorials buds.
I notice lots of people are raising an error instead of ignoring or returning null so they have failed the challenge's instructions.
Ruby
I think you can get away with
string[1..-2]
there, Ben.BASH
I was surprised to find that
-1
to work as well:Rust
View it in the Rust Playground here: play.rust-lang.org/?version=stable...
I tried to not use any str function.
I wanted to take my chances with these challenges, but I decided to start from the beginning, so here's my (super) late entry, done in Java :
in C# as Extension-Method
PHP
I like that substr trick with the -1, didn't think of that!
How about this one liner?
Use mb_string to support multibyte chars, such as Chinese
Also typehinted the argument, you never know...
This one is even shorter, possible only if the arg is typehinted tho
When the string is shorter than 2, substr returns false;
when the length is 2, substr returns "".
In both cases it's false, the the return is null.
Edit: many typos, I'm on mobile :/
Ruby
Basic
Extra
In C#, I would use in built string function Trim()
In my opinion we don't need Substring() here.
Just call :
With 2 length validation:
But what if the input would be "aaajldflbbb"?
When using Trim(char[]), all appearances of the characters given to the method at the beginning and at the end, will be removed, leaving "jldfl".
Some comments may only be visible to logged-in visitors. Sign in to view all comments.