DEV Community

Daily Challenge #1 - String Peeler

dev.to staff on June 28, 2019

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 cho...
Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

CSS

Just add the class removeFirstAndLastLetter to a tag, and see the first and last letter "removed" from the text 😋

.removeFirstAndLastLetter {
  background: #fff;
  font-family: monospace;
  white-space: nowrap;
  position: relative;
  display: inline-block;
}

.removeFirstAndLastLetter::before,
.removeFirstAndLastLetter::after {
  content: "\00a0";
  background: #fff;
  top: 0;
  display: block;
  position: absolute;
  height: 100%;
  width: auto;
}

.removeFirstAndLastLetter::after {
  right: 0;
}
Enter fullscreen mode Exit fullscreen mode

And as an extra, it can be stylized and animated, so you can see the letters fade out:

Collapse
 
ben profile image
Ben Halpern

Ha! This one is great.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Thanks :)

Collapse
 
taillogs profile image
Ryland G • Edited

JavaScript

(someString) => someString.length > 2 ? someString.slice(1, -1) : undefined;
Enter fullscreen mode Exit fullscreen mode

Python

someString[1:-1] if len(someString) > 2 else None
Enter fullscreen mode Exit fullscreen mode

C++

someString.size() > 2 ? someString.substr(1, someString.size() - 1) : null;
Enter fullscreen mode Exit fullscreen mode

C

int trimString(char someString[])
{
  if (strlen(someString) > 2) {
    char *copy = malloc((strlen(someString) - 2) * sizeof(char));
    memmove (copy, someString + 1, strlen(someString) - 2);
    printf("%s", copy);
    free(copy);
    return 0;
  }
  return 1;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rafaacioly profile image
Rafael Acioly

Let people do something 😂

Collapse
 
jeromedeleon profile image
Jerome De Leon

HAHAHA damn. Let me finish my code LOL.

Collapse
 
powerc9000 profile image
Clay Murray • Edited

Let's just go wild

(someString) => {
   switch(someString.length){
   case 0:
   case 1:
   case 2:
       return null;
   default:
       const arr = someString.split("")
       arr.pop();
       arr.reverse();
       arr.pop();
       arr.reverse();
       return arr.join("")
   }
}

Why not?

Collapse
 
aybee5 profile image
Ibrahim Abdullahi Aliyu

This is indeed wild

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

In JavaScript it could be 24 bytes:

f=s=>s.slice(1,-1)||null
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andrewbrown profile image
Andrew Brown 🇨🇦 • Edited

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.
def quartered value
  raise ArgumentError, 'Argument is not a string' unless value.is_a? String
  return value unless value.size > 2
  value[0] = ''
  value.chop
end


class QaurteredTest < Test::Unit::TestCase
  def test_quartered
    assert_equal 'orl', quartered('world'), "quartered('world') should return a string called 'orl'"
  end

  def test_quartered_ignore
    assert_equal 'hi', quartered('hi'), "quartered('hi') should return 'hi'"
  end

  def test_quartered_invalid
    assert_raise_message('Argument is not a string', "quartered(2) should raise exception") do
      quartered(2)
    end
  end
end
Collapse
 
ben profile image
Ben Halpern • Edited

Ruby


def remove_first_and_last(string)
  raise "Invalid" if string.size < 3
  string[1..string.size-2]
end
Collapse
 
databasesponge profile image
MetaDave 🇪🇺

I think you can get away with string[1..-2] there, Ben.

Collapse
 
v613 profile image
Ceban Dumitru • Edited

BASH

if [[ ${#1} > 2 ]]; then
    echo "${1:1:$(($#1-2))}";
else echo "not validated";
fi
Collapse
 
orenovadia profile image
orenovadia • Edited

I was surprised to find that -1 to work as well:

V=abcde
echo "${V:1:-1}"
Collapse
 
coreyja profile image
Corey Alexander • Edited

Rust

fn remove_first_and_last(string: &str) -> &str {
    remove_first_and_last_n_chars(&string, 1)
}

fn remove_first_and_last_n_chars(string: &str, chars_to_remove: usize) -> &str {
    if string.len() <= (2 * chars_to_remove) {
        panic!("Input string too short")
    }
    let start = chars_to_remove;
    let end = string.len() - 1 - chars_to_remove;

    &string[start..end]
} 

fn main() {
    println!("Ans: {}", remove_first_and_last("Hello, world!"));
    println!("Ans: {}", remove_first_and_last_n_chars("Hello, world!", 2));
    println!("Ans: {}", remove_first_and_last_n_chars("aa", 1));
    println!("Ans: {}", remove_first_and_last_n_chars("aa", 2));
}

View it in the Rust Playground here: play.rust-lang.org/?version=stable...

Collapse
 
overlordex3 profile image
Exequiel Beker

I tried to not use any str function.

char* trimFirstAndLastLetters(char* str)
{
    int index = 1;

    if(str[0] == '\0' || str[1] == '\0') {
        return NULL;
    }

    while(*(str + index) != '\0') {
        *(str + (index - 1)) = *(str + index);
        index++;
    }

    /* Remove last one */
    *(str + (index - 2)) = '\0';
    return str;
}
Collapse
 
barbaraips profile image
Bárbara Perdigão • Edited

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 :

public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Type the word:");
        String word = scan.nextLine();

        if (word.length() > 2) {
            System.out.printf("Result: %s%n", word.substring(1, word.length() - 1));
        } else {
            System.out.println("Invalid word.");
        }

}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andreasjakof profile image
Andreas Jakof

in C# as Extension-Method

public static string Peel(this string toPeel)
{
    int residual = toPeel.Length -2;
    if (residual < 1) return null;

    return toPeel.SubString(1,residual); //skip the first and take all but the last char
}
Collapse
 
vguleaev profile image
Vladislav Guleaev • Edited
function removeChar(str){
 return str.substr(1, str.length - 2)
};
Collapse
 
coreyja profile image
Corey Alexander • Edited

Ruby

Basic

def remove_first_and_last(some_string)
  raise 'Not long enough' unless some_string.length > 2

  some_string[1..-2]
end

Extra

def remove_first_and_last_n_characters(some_string, chars_to_remove: 1)
  raise 'Not long enough' unless some_string.length > (chars_to_remove * 2)

  start_index = chars_to_remove
  end_index = -1 - chars_to_remove
  some_string[start_index..end_index]
end
Collapse
 
martyhimmel profile image
Martin Himmel

PHP

function remove_string_ends($str) {
    if (strlen($str) <= 2) {
        return null;
    }
    return substr($str, 1, -1);
}
Collapse
 
claudioscatoli profile image
Claudio Scatoli • Edited

I like that substr trick with the -1, didn't think of that!

How about this one liner?

<?php

function trimThis(string $str)
{
    return (mb_strlen($str) <= 2) ? null : substr($str,1,-1);
}


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

<?php
function trimThis(string $str) {
    return substr($str,1,-1) ?: null;
}

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 :/

Collapse
 
johncip profile image
jmc

Clojure:

(defn trim [s]
  (apply str (drop-last (rest s))))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rafi993 profile image
Rafi • Edited

solution in SQL (postgres)

\set str 'hello world'

select (
     case
       when (select length(:'str') > 2) 
        then (select substr(:'str', 2, length(:'str') - 2) ) 
else 'invalid string' end );
Collapse
 
kaspermeyer profile image
Kasper Meyer • Edited

Ruby solution

require "minitest/autorun"

class WordTrimmer
  def initialize word
    @word = word
  end

  def trim
    @word.length <= 2 ? @word : @word[1..-2]
  end
end

class WordTrimmerTest < MiniTest::Test
  def test_removing_first_and_last_letter
    assert_equal "aspe", WordTrimmer.new("kasper").trim
  end

  def test_ignoring_two_letter_word
    assert_equal "hi", WordTrimmer.new("hi").trim
  end

  def test_ignoring_one_letter_word
    assert_equal "I", WordTrimmer.new("I").trim
  end
end
Collapse
 
mwlang profile image
Michael Lang

Ruby Language Version

With specs

def trim value
  value.to_s[1...-1]
end

require "spec"

describe "#trim" do
  it { expect(trim "Foo Bar").to eq "oo Ba"}
  it { expect(trim "Foo").to eq "o"}
  it { expect(trim "Fo").to eq ""}
  it { expect(trim "F").to eq ""}
  it { expect(trim nil).to be_nil}
  it { expect(trim 777).to eq "7"}
end

output

>> rspec debook_ends.rb
......

Finished in 0.00696 seconds (files took 0.15187 seconds to load)
6 examples, 0 failures
Collapse
 
lessp profile image
Tom Ekander

ReasonML

let strip = text =>
  String.(
    length(text) > 2
      ? switch (sub(text, 1, length(text) - 2)) {
        | s => Some(s)
        | exception _ => None
        }
      : None
  );

strip("hello"); // Some("ell")
strip("ab"); // None
strip(""); // None
Collapse
 
praneetnadkar profile image
Praneet Nadkar • Edited

In C#, I would use in built string function Trim()
In my opinion we don't need Substring() here.
Just call :

readedInput.Trim(readedInput[0], readedInput[readedInput.Length - 1])

With 2 length validation:

var trimmed = readedInput.Length > 2 ? readedInput.Trim(readedInput[0], readedInput[readedInput.Length - 1]) : "Invalid" ;
Collapse
 
andreasjakof profile image
Andreas Jakof

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

Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.

Collapse
 
celyes profile image
Ilyes Chouia • Edited

PHP:


function removeFirstAndLastLetter($text){
    return substr($text, 1, -1);
}
echo removeFirstAndLastLetter("Oh no, I lost two letters");

// Outputs : h no, I lost two letter


Collapse
 
georgeoffley profile image
George Offley • Edited

Off the top of the head in Python 🐍🐍🐍🐍

def strip_first_last(string):
     if len(string) > 2:
          return string[1:-1]
     else:
          return None

print(strip_first_last("Hello World"))
Collapse
 
pmkroeker profile image
Peter

Solution in Go:

package main

import (
    "fmt"
)

func main() {
    p, err := peel("hello")
    if err != nil {
        panic(err)
    }
    fmt.Println(p)
}

func peel(s string) (string, error) {
    if len(s) < 3 {
        return "", fmt.Errorf("Input string too short")
    }
    return s[1 : len(s)-1], nil
}

Running example in Go Playground

Collapse
 
hevivekm profile image
Vivek

Swift - 5

var str = "Hello, playground"
func stringPeeler(input: String) -> String? {
    if (input.count <= 2) {
        return nil;
    }

    return String(input.dropLast().dropFirst())
}

print(stringPeeler(input: str)!)
Collapse
 
aaron_stroud profile image
Aaron Stroud

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 string
function removeFirstLastLetters(str) {
  if (str.length < 3) {
    return null;
  }
  else {
    const regex = /[a-zA-Z]/;

    let firstCharIndex = str.search(regex);

    if (firstCharIndex === -1 ) {
      return null;
    }

    else {
      let lastCharIndex = str.length - str.split("").reverse().join("").search(regex);

      return str.slice(0, firstCharIndex) + str.slice(firstCharIndex + 1, lastCharIndex - 1) + str.slice(lastCharIndex, str.length);
    }
  }
}
Collapse
 
werner profile image
Werner Echezuría

Rust

fn trim_string(string: &str) -> &str {
    if string.len() <= 2 {
        panic!("Input string too short");
    }
    &string[1..string.len() - 1]
}
Collapse
 
kesprit profile image
kesprit

Swift

func removeFirstAndLastLetter(value: String) -> String? {
    guard value.count > 3 else { return nil }
    var result = value.dropFirst()
    result.popLast()
    return String(result)
}
Collapse
 
kerldev profile image
Kyle Jones

In Python:

def peel_string(text):
    if len(text) > 2:
        return text[1:(len(text) - 1)]
    return None

print(peel_string("Testing"))
print(peel_string("Hi"))
print(peel_string(""))
Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

Trivial in Ruby:

def double_chop(string)
  return string if string.length <= 2
  string[1..-2]
end

double_chop("hello world") # => "ello worl"
double_chop("book")        # => "oo"
double_chop("OOP")         # => "O"
double_chop("hi")          # => "hi"
Collapse
 
viniciuscavagnolli profile image
Vinicius Cavagnolli

VB5 / VB6

Function Challenge1(input As String) As String
    If len(input) <= 2 Then
        Challenge1 = Nothing
    Else
        Challenge1 = Mid$(input, 2, len(input) - 2) 
    End If
End Function

Visual Basic .NET

Function Challenge1(input as String)
    Return If(input.Length > 2, Mid(input, 2, len(input) - 2), Nothing)
End Function

C#

string Challenge1(string input) => input.Length > 2 ? input.Substring(1, input.Length - 2) : null;

C# using LINQ (because yes)

string Challenge1(string input) => input.Length > 2 ? string.Concat(input.Skip(1).Take(input.Length - 2)) : null;
Collapse
 
scrabill profile image
Shannon Crabill

I liked today's challenge so I'm going back to do past ones

def string_peeler(string)
  if string.length > 2
    string.delete(string[0]).delete(string[-1])
  end
end

Returns

string_peeler("hi") => nil 
string_peeler("killer") => "ille" 
string_peeler("BOB") => "O" 
Collapse
 
jasman7799 profile image
Jarod Smith

// "enterprise" solution
function peelString(str = '')
{
  //validate
  if(typeof(str) != 'string')
    throw new Error(`${str}, ${typeof(str)} is not a string`);
  if(str.length <= 2)
    throw new Error(`${str} does not have atleast 3 letters`);

  // process
  return str.substring(1,str.length-1);
}

My "enterprise" solution

Collapse
 
rvictorino profile image
Robin Victorino • Edited

Hi!

A bit late to the party, but here's a Groovy one:

String peel(String toPeel) {
    if(!(toPeel?.length() > 2)) {
        throw new Exception('Can\'t peel a string shorter than 3 characters')
    }
    return toPeel[1..-2]
}
Collapse
 
flamangoes profile image
flamangoes

My approach in groovy...

Not sure if "ignore <2 chars" means "don't consider" or "ignore the trimming"

Don't consider =>

String peel(String toPeel) {
    toPeel[1..-2]
}

Ignore =>

String peel(String toPeel) {
    toPeel?.length() >2 ? toPeel[1..-2] : toPeel
}

I don't like returning null.

Collapse
 
anilkhandei profile image
Anil Kumar Khandei

I am so many months late in the game so starting with the first one.

 public static string StringPeeler(string InputStr)
        {
            if (InputStr.Length <= 2)
            {
                return "invalid";
            }
            else
            {
                return InputStr.Substring(1, InputStr.Length - 2);
            }
        }

And also unit tested the same:

 [TestMethod]
        public void StringPeeler_InvalidTest()
        {
           var result= DEVToChallenges.StringPeeler("a");

            Assert.IsTrue(result == "invalid");
        }
        [TestMethod]
        public void StringPeeler_InvalidTestTwo()
        {
            var result = DEVToChallenges.StringPeeler("an");

            Assert.IsTrue(result == "invalid");
        }

        [TestMethod]
        public void StringPeeler_InvalidTestThree()
        {
            var result = DEVToChallenges.StringPeeler("ant");

            Assert.IsFalse(result == "invalid");
        }

        [TestMethod]
        public void StringPeeler_ValidTestOne()
        {
            var result = DEVToChallenges.StringPeeler("cobol");

            Assert.IsTrue(result == "obo");
        }
Collapse
 
devendradhanal profile image
Devendra Dhanal
const stringTrimmer = input => input.length <=2 ? null : input.substring(1, input.length - 1)



console.log(stringTrimmer("Lorem Ipsum")) // orem Ipsu
console.log(stringTrimmer("John Doe")) // ohn Do
console.log(stringTrimmer("Fox jumps over")) // ox jumps ove
console.log(stringTrimmer("Lorem")) // ore
console.log(stringTrimmer("Lo")) // null
Collapse
 
gnsp profile image
Ganesh Prasad

const test = require ('./tester');

const f = str => str.length > 2 ? str.slice(1, -1) : null;
test (f, [
    {
        in: ['Dev'],
        out: 'e',
    },
    {
        in: ['GP'],
        out: null,
    },
    {
        in: ['hello'],
        out: 'ell'
    }
]);

[PASSED]  Case #1: e
[PASSED]  Case #2: null
[PASSED]  Case #3: ell

Collapse
 
bugmagnet profile image
Bruce Axtens

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.

public static string StringPeeler(string str) => string.Join("", from ch in str.ToCharArray(1, str.Length - 2) select ch);
Collapse
 
mbaas2 profile image
Michael Baas

APL (using Dyalog APL)

as a direct function:

      peeler←{1↓¯1↓⍵}

Testing it

      peeler 'Works'
ork

Try it online!

Collapse
 
mellamoadan profile image
Adan ϟ

I'll start doing this challenges in Dart :D

import 'dart:io';

main() {
  stdout.writeln('Phrase?');
  String phrase = stdin.readLineSync();
  phrase.length > 2 ? print(phrase.substring(1, phrase.length - 1)) : print('Invalid Phrase');
}

Collapse
 
gypsydave5 profile image
David Wickes

Factor

USING: kernel math sequences ;
IN: dev.to-daily-challenge

: not-first-and-last ( str -- str ) dup length 2 >  [ rest but-last ] [ ] if ;

and some tests

USING: tools.test dev.to-daily-challenge ;
IN: dev.to-daily-challenge.tests

{ "ell" } [ "hello" not-first-and-last ] unit-test
{ "e" } [ "hel" not-first-and-last ] unit-test
{ "ha" } [ "ha" not-first-and-last ] unit-test
{ "" } [ "" not-first-and-last ] unit-test
Collapse
 
peterbunting profile image
Peter Bunting

In F#. Not the most straightforward way to solve this, but I wanted to use the language Array splicing.

let stringToByteArray (s:string)= System.Text.Encoding.ASCII.GetBytes s
let byteArraySplice x y (b: byte[]) = b.[x..y]
let byteArrayToString (b: byte[]) = System.Text.Encoding.ASCII.GetString b

let stringPeeler s = 
    s
    |> stringToByteArray
    |> byteArraySplice 1 (s.Length - 2)
    |> byteArrayToString

printfn "%s" <| stringPeeler "abcdefgh"
printfn "%s" <| stringPeeler "ab"
printfn "%s" <| stringPeeler "a"
Collapse
 
peterbunting profile image
Peter Bunting

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:

let stringPeeler (s: string) = s.[1..(s.Length - 2)]
Collapse
 
tblanshard profile image
Tallie

My solution using Python and list comprehension :)

def stringPeeler(string_to_peel):
    if len(string_to_peel) > 2:
        return "".join([x for i, x in enumerate(list(string_to_peel)) if (len(string_to_peel) - 1) > i > 0])
    else:
        return None
Collapse
 
figueroadavid profile image
David Figueroa

Powershell

function Remove-FirstAndLastCharacter {
    param(
        [parameter(Mandatory,ValueFromPipelineByName)]
        [string]$Input
    )
    if ($Input.length -ge 3)
    { 
        return $Input.SubString(1,$Input.Length - 2)
    }
}
Collapse
 
rodrigoords profile image
Rodrigo Sene

JAVA

public class Solution {

    public static String getStringCore(String input){
        if(input.length() > 2){
            return input.substring(1, input.length() -1);
        }
        return "invalid input";
    }

    public static void main(String[] arg){
        System.out.println(Solution.getStringCore("let's do it agin"));
    }
}
Collapse
 
chukkyiii profile image
Jesse Doka • Edited

Python

def string_peeler(string):
    stringarr = []
    newstring = ''

    for x in string:
        stringarr.append(x)

    del(stringarr[0])
    del(stringarr[-1])

    for em in stringarr:
        newstring += em
    print(newstring)

string_peeler('Missing two letters')

Collapse
 
iagocavalcante profile image
Iago Angelim Costa Cavalcante

Elixir

def remove_primeiro_ultimo_caracteres(string, caracter_removido \\ 1) do
    unless String.length(string) > (caracter_removido * 2) do
      raise 'Tamanho da string é menor que 2'
    end

    inicio = caracter_removido
    fim = -1 - caracter_removido
    String.slice(string, inicio..fim)
  end
Collapse
 
adusoft profile image
Geofrey Aduda • Edited

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");
}
}

Collapse
 
margo1993 profile image
margo1993

Yesterday I started to discover golang, so i try do make these daily challenges in go.

My simple go solution

func RemoveFirstAndLastCharacterInWord(word string) (string, error) {
    wordLen := len(word)
    if wordLen < 3 {
        return "", errors.New("String: word is too short")
    }
    return word[1 : wordLen-1], nil
}
Collapse
 
mrdulin profile image
official_dulin

Go:

package kata

func RemoveChar(word string) string {
  return word[1:len(word)-1]
}
Collapse
 
karthicktamil17 profile image
karthick rajan • Edited

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"

Collapse
 
caleb_rudder profile image
Caleb Rudder • Edited

C++ that takes user input

string prompt = "Enter a string: ";
string userInput;

cout << prompt << endl;
getline(cin,userInput);

if (userInput.length() > 2) {

    userInput = userInput.substr(1, (userInput.length() - 2));

}

cout << userInput;
Collapse
 
jenc profile image
Jen Chan • Edited

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

Collapse
 
khaloscar profile image
khaloscar • Edited

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.

fn peel_string(input: &str) -> Result<&str, Box<dyn Error>> {
    let output = match input.len() {
        3..=16 => Ok(&input[1..input.len() - 1]),
        len if len > 16 => Err("Input too long, should be 3-16 chars".into()),
        len if len == 0 =>Err("No input, should be 3-16 chars".into()),
        _ => Err("Input too short, should be 3-16 chars".into()),
    };

    output
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rafaacioly profile image
Rafael Acioly

Go

func strip(content string) (string, error){
    if len(content) <= 2 {
        return "", error.New("invalid length")
    }

    return content[1:len(content)-1], nil
}        
Collapse
 
rachit995_97 profile image
Rachit Sharma

Too late to the wagon, but here.

JS:

function peeler(str){
    return str.length > 2 ? str.slice(1).slice(0, str.length - 2) : null
}
Collapse
 
hraverkar profile image
Harshal Raverkar
private void RemoveFirstandLast(string str){

str = str.Substring(1,str.Length-2);
Console.WriteLine(str);
}

Collapse
 
diegous profile image
diegous

Haskell

middleChars :: String -> String
middleChars = tail . dropLast
            where dropLast (last:[])   = []
                  dropLast (head:tail) = head : (dropLast tail)
Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell:

removeFirstAndLast :: [a] -> Maybe [a]
removeFirstAndLast xs 
  | length xs < 3 = Nothing 
  | otherwise = Just $ init $ tail xs

As a bonus, it works on any type of list

Collapse
 
hevivekm profile image
Vivek • Edited

Javascript

const stringPeeler = str => {
  if (undefined === str || null === str || 2 >= str) {
    throw new Error('Invalid String');
  }

  return str.slice(1, -1);
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bauripalash profile image
Palash Bauri 👻

Here The Journey Begins.. 🚀

Python

def challenge1(s):
    if len(s)<2:
        return None
    else:
        return s[1:-1:]
Collapse
 
rafi993 profile image
Rafi

Rust

fn main() {
  let input = "Hello, world!";
  let output = &input[1..(input.len() - 1)];
  println!("{}", output);
}
Collapse
 
pochirajuanirudh profile image
pochirajuAnirudh

Python 3

def remove_first_and_last_characters(input_string):
    if len(input_string) < 3 or type(input_string) != str:
        return "invalid"
    return input_string[1:-1]
Collapse
 
skeptycal profile image
Michael Treanor

Python:

code:

import sys
print("\n".join([arg[1:-1] for arg in sys.argv[1:] if len(arg) > 2]))

example:

# example

❯ ./first_and_last.py this is a bad example
hi
a
xampl
Collapse
 
spyrosko profile image
spyrosko • Edited
function word(str) {

   let i = str.slice(1, -1);

   if (i) {
      return i;
   } else {
      return 'null';
   }
}
Collapse
 
deciduously profile image
Ben Lovy

I'm late to the party, catching up one by one!

Haskell:

trimAtBothEnds :: String -> Maybe String
trimAtBothEnds s = if ((length s) <= 2) then Nothing else Just (init.tail $ s)
Collapse
 
torianne02 profile image
Tori Crawford

Ruby

def remove_char(s)
  raise "invalid string" if s.size < 3

  return s[1..-1].chop
end
Collapse
 
highcenburg profile image
Vicente G. Reyes • Edited

Python

def remove(yo):
    if yo <= 2:
        print("Not enough characters in string")
    else:
    return yo[1:-1]
Collapse
 
aritdeveloper profile image
Arit Developer

Ruby

def first_last_gone(string)
    return "Invalid Entry" unless string.length > 2
    string.slice!(0)
    string.slice!(-1)
    string
end
Collapse
 
mdarrik profile image
Darrik Moberg

R

peel <-function(inputString) {
  ifelse(nchar(inputString) <=2, NA,
 substr(inputString,2,nchar(inputString)-1))
}

Natively works on matrices/vectors of strings, which is cool.

Collapse
 
hraverkar profile image
Harshal Raverkar
private void RemoveFirstandLast(string str){

str = str.Substring(1,str.Length-2);
Console.WriteLine(str);
}
Collapse
 
willsmart profile image
willsmart

Seat of your pants GNU C

printf(“String: %s”, s);
printf(“ trin : %s”, ({s[strlen(s)-1]=0;s+1;}));

(untested, also a bad idea in multiple ways)

Collapse
 
jordonr profile image
Jordon Replogle

Perl?

$testing = "Happy coding!";
print &peeler($testing) . "\n";

sub peeler {
    my $str = shift;
    if(length($str) > 2) {
        return substr($str, 1, -1);
    }
}

Collapse
 
choroba profile image
E. Choroba

Or maybe just

sub peeler { shift =~ s/^.|.$//gr }
Collapse
 
hraverkar profile image
Harshal Raverkar

if (str.Length <= 2) return;
var t = str.Substring(1, str.Length - 2);
Console.Write(t);

Collapse
 
olragon profile image
Long Nguyen

Javascript

function removeFirstAndLast(txt) {
  if (typeof txt != "string" || !txt || txt.length < 2) {
    return null;
  }
  return txt.slice(1, txt.length - 1);
}
Collapse
 
ronakjethwa profile image
Ronak Jethwa
function remove_ends(str) {
    return str.length <= 2 ? null : str.substr(1,str.length-2);
}
remove_ends("string");
Collapse
 
cloudyhug profile image
cloudyhug

Haskell

removeFirstAndLast :: String -> String
removeFirstAndLast s
  | length s <= 2 = s
  | otherwise     = init $ tail s
Collapse
 
stevemoon profile image
Steve Moon

Erlang

fltrim (Input) when length(Input) > 2 ->
    string:slice(Input, 1, length(Input) - 2).
Collapse
 
webcoderph profile image
Maynard Cabalitan • Edited

Ruby

def trimmer(str)
  str.length  > 2  ? str[1..-2] : 'invalid'
end

Or

class String
  def trimmer
    self.length > 2 ? self[1..-2] : 'invalid'
  end
end
Collapse
 
kvharish profile image
K.V.Harish

My solution in js


const stringPeeler = (str) => str.length > 2 ? str.substr(1, str.length - 2) : `Invalid input to stringPeeler function ${str}`;

Collapse
 
jeddevs profile image
Theo • Edited

The SmEXy python.

ToModify = input("Input:")
size = len(ToModify)
if size > 2:
  print(ToModify[1:-1])
else:
   print("String can't be less than two characters")
Collapse
 
akash746 profile image
Akash Deep

Java:

someString.length()<=2?someString:someString.substring(1,someString.length()-1)

Collapse
 
kdinnypaul profile image
Dinny Paul • Edited

I think Javascript is the most efficient line liner, I have also added trim :) to take care of extra white spaces

console.log(" String ".trim().slice(1,-1)||null);
Collapse
 
nedyudombat profile image
Nedy Udombat

Javascript

const strip = (string) => {
  if(string.length <= 2) return 'Invalid'
  return string.substring(1, string.length-1)
}
Collapse
 
sachindra149 profile image
sachindra@work

function stringPeeler(str) {
return str.length > 2 ? str.substr(1, str.length-2) : 'Invalid String'
}

Collapse
 
centanomics profile image
Cent

JS

Codepen


const stringPeeler = text => {
  return text.length < 3 ? null : text.substr(1, text.length-2);
}

Collapse
 
lakdivian profile image
Noorul Ameen K M

const strig_slicer = (some_string) => some_string.length >= 2 : some_string.slice(1,-1) : null

Collapse
 
dimitrilahaye profile image
Dimitri Lahaye

Here in JS

function remove(str) {
  if (str.length >= 3) {
    return str.slice(1, -1);
  }
}
Collapse
 
mahajanmohit profile image
Mohit Mahajan

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])

Collapse
 
davejs profile image
David Leger
const peelString = (s: string): string => {
  return s.length > 2 ? s.slice(1, -1) : null;
}
Collapse
 
peter279k profile image
peter279k

Here is my simple solution :).

function removeChar(str){
 //You got this!
  return str.substr(1, str.length-2);
};
Collapse
 
ronakjethwa profile image
Ronak Jethwa
return str.length > 2 ? str.slice(1,str.length-1) : str;
Collapse
 
webdevhill profile image
Jeffrey Hill

JS

const str => str.length > 2 ? str.slice(1, -1) : undefined;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
albakalymuf profile image
mufadhal • Edited

Javascript :
s1 = s.length > 2 ? s.slice(1,s.length-1):null

Collapse
 
codefinity profile image
Manav Misra
Collapse
 
ujadhav25 profile image
Umesh Jadhav

javascript

(function (str) {
if (str.length <= 2) {
return null;
}
console.log(str.slice(1, str.length - 1));
})('cut me from start and end')

Collapse
 
anfossistudio profile image
AnfossiStudio

JavaScript

Collapse
 
heebakhan6 profile image
heeba khan

this is very basic but i'm just a beginner :

a = "challenge of the day"

if (len(a)) > 2:
print( a[ 1 : len(a)-1])
else :
print(a)

Collapse
 
rahul0706 profile image
rahul0706

public static String removeFirstAndLastLetter(String str) {
if(str.length()>2) {
return str.substring(1, str.length()-1);
}
return null;
}

Collapse
 
mahajanmohit profile image
Mohit Mahajan

I am new to coding world, so my code might not be that efficient but i am happy with the fact that i have completed it.

Collapse
 
motss profile image
Rong Sen Ng

Just to clarify. Can any given string contain whitespace character? What is the expected output of " \r\n"?

Collapse
 
hraverkar profile image
Harshal Raverkar

if (str.Length <= 2) return;
var t = str.Substring(1, str.Length - 2);
Console.Write(t);