DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #1 - String Peeler

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)

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

Some comments may only be visible to logged-in visitors. Sign in to view all comments.