Head of Product at Temporal. Previously lead architect and low-level systems programmer for scale out SaaS offering. Game engine developer, ML engineering expert. DMs open on Twitter.
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.
require"test/unit"# remove the first and last letter of a string# if there is less than 2 characters return zero.defquarteredvalueraiseArgumentError,'Argument is not a string'unlessvalue.is_a?Stringreturnvalueunlessvalue.size>2value[0]=''value.chopendclassQaurteredTest<Test::Unit::TestCasedeftest_quarteredassert_equal'orl',quartered('world'),"quartered('world') should return a string called 'orl'"enddeftest_quartered_ignoreassert_equal'hi',quartered('hi'),"quartered('hi') should return 'hi'"enddeftest_quartered_invalidassert_raise_message('Argument is not a string',"quartered(2) should raise exception")doquartered(2)endendend
char*trimFirstAndLastLetters(char*str){intindex=1;if(str[0]=='\0'||str[1]=='\0'){returnNULL;}while(*(str+index)!='\0'){*(str+(index-1))=*(str+index);index++;}/* Remove last one */*(str+(index-2))='\0';returnstr;}
publicstaticstringPeel(thisstringtoPeel){intresidual=toPeel.Length-2;if(residual<1)returnnull;returntoPeel.SubString(1,residual);//skip the first and take all but the last char}
defremove_first_and_last(some_string)raise'Not long enough'unlesssome_string.length>2some_string[1..-2]end
Extra
defremove_first_and_last_n_characters(some_string,chars_to_remove: 1)raise'Not long enough'unlesssome_string.length>(chars_to_remove*2)start_index=chars_to_removeend_index=-1-chars_to_removesome_string[start_index..end_index]end
Full stack web dev.
Studying FP web development approaches, while helping Mission Bit create paths to programming for underserved public school kids.
Previously @ Gradescope.
// "enterprise" solutionfunctionpeelString(str=''){//validateif(typeof(str)!='string')thrownewError(`${str}, ${typeof(str)} is not a string`);if(str.length<=2)thrownewError(`${str} does not have atleast 3 letters`);// processreturnstr.substring(1,str.length-1);}
functionremoveFirstAndLastLetter($text){returnsubstr($text,1,-1);}echoremoveFirstAndLastLetter("Oh no, I lost two letters");// Outputs : h no, I lost two letter
defremove_primeiro_ultimo_caracteres(string,caracter_removido\\1)dounlessString.length(string)>(caracter_removido*2)doraise'Tamanho da string é menor que 2'endinicio=caracter_removidofim=-1-caracter_removidoString.slice(string,inicio..fim)end
packagemainimport("fmt")funcmain(){p,err:=peel("hello")iferr!=nil{panic(err)}fmt.Println(p)}funcpeel(sstring)(string,error){iflen(s)<3{return"",fmt.Errorf("Input string too short")}returns[1:len(s)-1],nil}
Programmed Canon Canola calculators in 1977. Assorted platforms and languages ever since. Assisting with HOPL.info.
I am NOT looking for work -- I've got more than enough to do.
Location
Perth, WA Australia
Education
A few diplomas.
Work
Software Engineer at [Daisy Digital](https://daisydigital.com.au/)
I've only just stumbled over the Daily Challenge. Oh well, here's my C# Linq solution (different from the other one) and returns an empty string if length <= 2.
Second year Computer Science student with an interest in web/mobile development, big data, robotics and cyber security. Probably drinking too much coffee or coding to avoid doing other coding...
defstring_peeler(string):stringarr=[]newstring=''forxinstring:stringarr.append(x)del(stringarr[0])del(stringarr[-1])foreminstringarr:newstring+=emprint(newstring)string_peeler('Missing two letters')
I see a lot of solutions removing characters without checking to see if they're "letters." Here's my JavaScript solution.
// Remove the first and last _letters_ in a stringfunctionremoveFirstLastLetters(str){if(str.length<3){returnnull;}else{constregex=/[a-zA-Z]/;letfirstCharIndex=str.search(regex);if(firstCharIndex===-1){returnnull;}else{letlastCharIndex=str.length-str.split("").reverse().join("").search(regex);returnstr.slice(0,firstCharIndex)+str.slice(firstCharIndex+1,lastCharIndex-1)+str.slice(lastCharIndex,str.length);}}}
Im new to rust, and tried to get in some detailed error-handling.
Also added the functionality to not peel text that is too long as it does not make sense to me rn.
Maybe it would be better to take an String instead of &str as an argument, but idk.
fnpeel_string(input:&str)->Result<&str,Box<dynError>>{letoutput=matchinput.len(){3..=16=>Ok(&input[1..input.len()-1]),leniflen>16=>Err("Input too long, should be 3-16 chars".into()),leniflen==0=>Err("No input, should be 3-16 chars".into()),_=>Err("Input too short, should be 3-16 chars".into()),};output}
flremove val =
let
value = toCharArray val
value1 = Array.length value
in
if (length val > 2)
then do
show $ fromCharArray $ Array.slice 1 (value1 -1) value
else ""
main = render =<< withConsole do
log $ flremove "string"
By Profession Software Engineer. Works with MAPS, Google Maps, Cesium JS and Luciad Developer.
Proficient in C#, WPF, Angular, NodeJS, JavaScript, PGSQL
Full-stack dev shipping Django/React SaaS and Shopify stores since 2018. 37 client projects, 11 live Shopify builds. I write production war stories so you don’t repeat my outages.
I am new to the coding world so my code may not be that much efficient, but i am happy with the fact that i wrote it.
import sys
def trim_characters(input_string):
return_string=""
#print(return_string)
if (len(input_string))>2:
for i in range(0, len(input_string)):
if i!=0 and i!=len(input_string)-1:
return_string=return_string + input_string[i]
print("Output string : "+ return_string)
else:
print("Minnimum 3 characters are allowed")
trim_characters(sys.argv[1])
Displaying a subset of the total comments. Please sign in to view all comments on this post.
CSS
Just add the class
removeFirstAndLastLetterto 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
-1to work as well:I tried to not use any str function.
Rust
View it in the Rust Playground here: play.rust-lang.org/?version=stable...
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
Ruby solution
solution in SQL (postgres)
Ruby Language Version
With specs
output
ReasonML
Clojure:
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".
Rust
VB5 / VB6
Visual Basic .NET
C#
C# using LINQ (because yes)
JAVA
Hi!
A bit late to the party, but here's a Groovy one:
My approach in groovy...
Not sure if "ignore <2 chars" means "don't consider" or "ignore the trimming"
Don't consider =>
Ignore =>
I don't like returning null.
Trivial in Ruby:
I liked today's challenge so I'm going back to do past ones
Returns
My "enterprise" solution
PHP:
Elixir
Solution in Go:
Running example in Go Playground
APL (using Dyalog APL)
as a direct function:
Testing it
Try it online!
Swift
Factor
and some tests
I've only just stumbled over the Daily Challenge. Oh well, here's my C# Linq solution (different from the other one) and returns an empty string if length <= 2.
I'll start doing this challenges in Dart :D
I am so many months late in the game so starting with the first one.
And also unit tested the same:
My solution using Python and list comprehension :)
In F#. Not the most straightforward way to solve this, but I wanted to use the language Array splicing.
And it turns out that you don't even need to explicitly convert it to an array. F# will let you do splicing on a string. So a much better solution is:
Swift - 5
Powershell
In Python:
Python
I see a lot of solutions removing characters without checking to see if they're "letters." Here's my JavaScript solution.
Off the top of the head in Python 🐍🐍🐍🐍
Handwrote my answer to practice:
const firstLast = (str) => {
const letters = [...str];
if (letters.length <=2){
return null;
}
let trimmed = letters.shift().pop();
return trimmed.join('');
}
Now to see if it works...
Im new to rust, and tried to get in some detailed error-handling.
Also added the functionality to not peel text that is too long as it does not make sense to me rn.
Maybe it would be better to take an String instead of &str as an argument, but idk.
Purescript
flremove val =
let
value = toCharArray val
value1 = Array.length value
in
if (length val > 2)
then do
show $ fromCharArray $ Array.slice 1 (value1 -1) value
else ""
main = render =<< withConsole do
log $ flremove "string"
java function using string builder
public String removefirstWordLastWord(String mystring )
{
///Delete last and first character
StringBuilder chr=new StringBuilder(mystring);
String strresult="";
if (mystring.length()>=2)
{
chr.deleteCharAt(0);
chr.deleteCharAt(chr.length()-1);
strresult=chr.toString();
}else{
strresult=("Invalid String");
}
}
Yesterday I started to discover golang, so i try do make these daily challenges in go.
My simple go solution
Go:
C++ that takes user input
Go
function stringPeeler(str) {
return str.length > 2 ? str.substr(1, str.length-2) : 'Invalid String'
}
My solution in js
if (str.Length <= 2) return;var t = str.Substring(1, str.Length - 2);
Console.Write(t);
JS
Here is my simple solution :).
Python:
code:
example:
Here in JS
Haskell
Javascript
Rust
Python 3
Ruby
Or
Haskell:
As a bonus, it works on any type of list
Perl?
Or maybe just
Python
def remove(yo): if yo <= 2: print("Not enough characters in string") else: return yo[1:-1]I am new to the coding world so my code may not be that much efficient, but i am happy with the fact that i wrote it.
import sys
def trim_characters(input_string):
return_string=""
#print(return_string)
if (len(input_string))>2:
for i in range(0, len(input_string)):
if i!=0 and i!=len(input_string)-1:
return_string=return_string + input_string[i]
print("Output string : "+ return_string)
else:
print("Minnimum 3 characters are allowed")
trim_characters(sys.argv[1])
JS
Codepen
I'm late to the party, catching up one by one!
Haskell: