Daily Challenge #46 - ???

twitter logo ・1 min read

Daily Challenge (71 Part Series)

1) Daily Challenge #1 - String Peeler 2) Daily Challenge #2 - String Diamond 3 ... 69 3) Daily Challenge #3 - Vowel Counter 4) Daily Challenge #4 - Checkbook Balancing 5) Daily Challenge #5 - Ten Minute Walk 6) Daily Challenge #6 - Grandma and her friends 7) Daily Challenge #7 - Factorial Decomposition 8) Daily Challenge #8 - Scrabble Word Calculator 9) Daily Challenge #9 - What's Your Number? 10) Daily Challenge #10 - Calculator 11) Daily Challenge #11 - Cubic Numbers 12) Daily Challenge #12 - Next Larger Number 13) Daily Challenge #13 - Twice Linear 14) Daily Challenge #14 - Square into Squares 15) Daily Challenge #15 - Stop gninnipS My sdroW! 16) Daily Challenge #16 - Number of People on the Bus 17) Daily Challenge #17 - Double Trouble 18) Daily Challenge #18 - Triple Trouble 19) Daily Challenge #19 - Turn numbers into words 20) Daily Challenge Post #20 - Number Check 21) Daily Challenge #21 - Human Readable Time 22) Daily Challenge #22 - Simple Pig Latin 23) Daily Challenge #23 - Morse Code Decoder 24) Daily Challenge #24 - Shortest Step 25) Daily Challenge #25 - Double Cola 26) Daily Challenge #26 - Ranking Position 27) Daily Challenge #27 - Unlucky Days 28) Daily Challenge #28 - Kill the Monster! 29) Daily Challenge #29 - Xs and Os 30) Daily Challenge #30 - What is the price? 31) Daily Challenge #31 - Count IPv4 Addresses 32) Daily Challenge #32 - Hide Phone Numbers 33) Daily Challenge #33 - Did you mean...? 34) Daily Challenge #34 - WeIrD StRiNg CaSe 35) Daily Challenge #35 - Find the Outlier 36) Daily Challenge #36 - Let's go for a run! 37) Daily Challenge #37 - Name Swap 38) Daily Challenge #38 - Middle Name 39) Daily Challenge #39 - Virus 40) Daily Challenge #40 - Counting Sheep 41) Daily Challenge #41 - Greed is Good 42) Daily Challenge #42 - Caesar Cipher 43) Daily Challenge #43 - Boardgame Fight Resolver 44) Daily Challenge #44 - Mexican Wave 45) Daily Challenge #45 - Change Machine 46) Daily Challenge #46 - ??? 47) Daily Challenge #47 - Alphabets 48) Daily Challenge #48 - Facebook Likes 49) Daily Challenge #49 - Dollars and Cents 50) Daily Challenge #50 - Number Neighbor 51) Daily Challenge #51 - Valid Curly Braces 52) Daily Challenge #52 - Building a Pyramid 53) Daily Challenge #53 - Faro Shuffle 54) Daily Challenge #54 - What century is it? 55) Daily Challenge #55 - Building a Pile of Cubes 56) Daily Challenge #56 - Coffee Shop 57) Daily Challenge #57 - BMI Calculator 58) Daily Challenge #58 - Smelting Iron Ingots 59) Daily Challenge #59 - Snail Sort 60) Daily Challenge #60 - Find the Missing Letter 61) Daily Challenge #61 - Evolution Rate 62) Daily Challenge #62 - Josephus Survivor 63) Daily Challenge #63- Two Sum 64) Daily Challenge #64- Drying Potatoes 65) Daily Challenge #65- A Disguised Sequence 66) Daily Challenge #66- Friend List 67) Daily Challenge #67- Phone Directory 68) Daily Challenge #68 - Grade Book 69) Daily Challenge #69 - Going to the Cinema 70) Daily Challenge #70 - Pole Vault Competition Results 71) Daily Challenge #71 - See you next Happy Year

Today's challenge requires you to write a function which removes all question marks from a given string.

For example: hello? would be hello


This challenge comes from aikedaa here on DEV.

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

twitter logo DISCUSS (48)
markdown guide
 

I'll do:

echo $string | sed 's/?//g'

TrustmeI'manEngineer

 

Hey there! Nice to see some bash users here.

You can even use bash without sed using this little trick:

#!/usr/bin/env bash

string="??hello??"

echo $string # "??hello??"
echo ${string//\?/} # "hello"

Try it online.

See Manipulating String.

 

Are you aware of the fish shell? I guess that you're pro+ in the bash, so I can't know about that. If not, check it out. You'll like that! It's a fully auto comopletion shell that is perfect for the home users. For scripts you'll still have to use bash though (ot tcsh, zsh whatsoever....) :)
If not you, hope so somebody will find it useful.

I've never had the courage to deep dive into the Fish shell honestly but your comment gave me some strength. I'll fire up a Docker container to test it out. Added to my ToDo list! Thanks.

 
 

sed is overkill. Try tr:

echo "why not use tr?" | tr -d '?'
 

Yap, he is right :)
I'm not yet a Senior developer.

 

ruby <3

def remove_question_marks(s)
  s |> delete ??
end
 

Ha, you probably confused some people there, especially with the character literal.

 

I love weird Ruby syntax😆

TIPS: ?? is known as character literal notation
docs.ruby-lang.org/en/trunk/syntax...

I know, that's why I wrote "especially with the character literal" ;-)

Other literals many people don't know are rational numbers (4/3r) and complex numbers (3+2i).

I see. Also % literal is my favorite string literal :)

s = %
here is string, the delimiter is \\n

puts s
 

x86_64 assembly (System V ABI, GNU assembler), as usual:

bsure.S:

    .global bsure

    .text
bsure:
    xor %eax, %eax
loop:
    mov (%rsi), %cl

    cmp $63, %cl # '?'
    je skip

    mov %cl, (%rdi)
    inc %rdi
    inc %rax
skip:
    inc %rsi

    cmp $0, %cl
    jne loop

    ret

bsure.h:

/* 
 * bsure - remove question marks from a string
 * if dst and src overlap (or match), that's fine
 * returns the number of bytes copied (including the null byte).
 */
size_t bsure(char *dst, char *src);
 

JavaScript

Here is my take to the challenge:

function removeQuestionMarks(input) {
  if (typeof input !== "string") {
    throw new TypeError("First argument expected to be a string");
  } 

  return input.split("?").join("");
}

console.log(removeQuestionMarks("hello?"));
// "hello"

console.log(removeQuestionMarks("hmm? hello??"));
// "hmm hello"

console.log(removeQuestionMarks("hmm? hello?? can i speak to the manager?"));
// "hmm hello can i speak to the manager"

console.log(removeQuestionMarks("?? is anybody there???"));
// " is anybody there"

Source-Code

Available online.

Side-note

By the name of the title in my notifications, I really though that the challenge would be to write a challenge and submit the best to the Dev.to team as they were running out of ideas. Haha!

 

By the name of the title in my notifications, I really though that the challenge would be to write a challenge and submit the best to the Dev.to team as they were running out of ideas. Haha!

Please submit challenge ideas! Simply email yo+challenge@dev.to with any proposals and we'll give you credit when we post it :)

 

Tomorrows challenge:

Write a random challenge generator!

 
 

Javascript:

const removeQuestionMark = string => string.replace(/\?/g, '')

Called as:

removeQuestionMark('Will this work???') // yes

Important to note, this will also remove the first escape characters (\) and output newlines in template literals as \n

 

Rust

fn no_questions (s: &str) -> String {
    s.chars().filter(|&c| c != '?').collect()
}

Playground

 
// CharacterRemover.java

package org.stringops.questionmarkremover;

public interface CharacterRemover {
    /**
     * TODO
     * @param String source TODO
     * @return String TODO
     */
    public String removeCharacter(String source);
}
// CharacterRemoverFactory.java

package org.stringops.questionmarkremover;

public interface CharacterRemoverFactory {
    /**
     * TODO
     * @return CharacterRemover TODO
     */
    public CharacterRemover createCharacterRemover();
}
// QuestionMarkRemover.java

package org.stringops.questionmarkremover;

import java.io.StringReader;
import java.io.InputStreamReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class QuestionMarkRemover implements CharacterRemover {
    /**
     * TODO
     * @param String source TODO
     * @return String TODO
     */
    public String removeCharacter(String source) {
        StringReader reader = new StringReader(source);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            int dataFromReader = reader.read();
            while (dataFromReader != -1) {
                if (dataFromReader != '?') {
                    outputStream.write(dataFromReader);
                }
                dataFromReader = reader.read();
            }
        } catch (IOException e) {
            // TODO: handle the exception
        }
        byte[] byteArray = outputStream.toByteArray();
        return new String(byteArray);
    }
}
// QuestionMarkRemoverFactory.java

package org.stringops.questionmarkremover;

public class QuestionMarkRemoverFactory implements CharacterRemoverFactory {
    /**
     * TODO
     * @return CharacterRemover TODO
     */
    public CharacterRemover createCharacterRemover() {
        return new QuestionMarkRemover();
    }
}

And to use it:

import org.stringops.questionmarkremover.*;

public class App {
    /**
     * TODO
     * @param String[] args TODO
     * @return void TODO
     */
    public static void main(String[] args) {
        CharacterRemoverFactory characterRemoverFactory = new QuestionMarkRemoverFactory();
        CharacterRemover characterRemover = characterRemoverFactory.createCharacterRemover();

        System.out.println(characterRemover.removeCharacter("hello?"));
    }
}
 
private static final OpinionAboutJava opinionAboutJava = OpinionAboutJavaFactory.getOpinionAboutJava("ugh...");
 

NOOOO!!!

You need to create an instance of the OpinionAboutJavaFactory! You can just have a static getOpinionAboutJava method! Now your code is not SOLID!

 
 

... 😐

I mean... that's not even a function to write. It's a function to call.

Elixir:

"What is this? What's happening??" |> String.replace("?", "")

Ruby:

"What is this? What's happening??".gsub("?", "")

JavaScript:

"What is this? What's happening??".replace(/\?/g, "")

Bash:

echo "What is this? What's happening??" | sed s/\?//g
 

Okay, I'll bite and imagine that Carmen Sandiego has stolen all the regular expressions!

defmodule DarnYouCarmen do
  # Quick, destroy the question marks before she steals them, too!
  def whats_a_question(string, processed \\ [])
  def whats_a_question("", processed), do: IO.chardata_to_binary(processed)
  def whats_a_question("?"<>string, processed), do: whats_a_question(string, processed)
  def whats_a_question(<<next :: utf8>> <> string, processed), do: whats_a_question(string, [processed, next]
end

DarnYouCarmen.whats_a_question("What is this? What's happening??")
# "What is this What's happening"
 

(javascript)

function noMoreQM(input)
{
  return input.replace(/\?/g, '');
}

Uses a simple regular expressions with the global (g) modifier to find all the ? (this needs to be escaped in a regular expression, so \?) and replace them with the empty string ''.

 

Ruby

def no_more_questions(string)
  string.gsub("?", "")
end
 
 

Hey there! Awesome to see some PHP users. PHP IS NOT DEAD! Haha.

But you are halfway done buddy!

Today's challenge requires you to write a function which removes all question marks from a given string.

 

okay okay let's do a wrapper function then :D

function myOwnStrReplaceBecauseIDontLikeSnakeCase($string) {
  return str_replace('?', '', $string);
}
 

Perl solution:

my $str = 'a?b?c?';
say $str =~ tr/?//dr;

The tr operator works like the tr shell util. /d means non-replaced characters are deleted, /r returns the value instead of modifying the bound variable.

 

Even though this is a simple one - it's really interesting to see all of the different ways you can do it!

But I agree with Josh - it's built into most languages :)

str.replace("?", "")
 
const questionToStatememt = str => str.replace(/\?+/g, '')
 

Haskell:

removeQuestionMarks :: String -> String
removeQuestionMarks = filter (/='?') 
 

Similar in Elm (but we have to use wrapping parenthesis for binary operators).

removeQuestionMarks : String -> String
removeQuestionMarks = String.filter ((/=) '?')
 
 

This one works for me. Since Bash doesn't support the global flag for regular expressions I had to iterate over the input string...

removeQuestionMark () {
    result=""
    while read -n 1 char ; do
        if [ "$char" != "?" ] ; then
            result="$result$char"
        fi
    done <<< $1
    echo $result
}

removeQuestionMark "h?e?l?l?o?" # prints "hello"
 
 

"the global flag in regular expression"
You've got regex for search in bash and regex for replace.
For replace, you've got sed. Are you familiar with sed? People usually skip it when learning bash for themselves on their own.

I intentionally avoided using sed this time, wanted to implement it with "pure" Bash. Using sed the implementation, of course, becomes much shorter.

 
const removeQuestionMarks = str => str.replace(/\?+/g,'');
 
 
System.out.println("??he?llo".replace("?", " "));


`

 

Well, since we're doing cmd things...

read s; echo "${s//\?/}"

(bash on mac)

 

PHP:

$string = "Some string with question marks??!!";
echo $string = str_replace("?", "", $string);
 

As simple as it sounds, in python :

lambda s : re.sub(r'\?','', s)
Classic DEV Post from Dec 12 '18

Silly Repos

eeeeeeee!

dev.to staff profile image
The hardworking team behind dev.to ❤️

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️