DEV Community

Daily Challenge #46 - ???

dev.to staff on August 21, 2019

Today's challenge requires you to write a function which removes all question marks from a given string. For example: hello? would be hello ...
Collapse
 
aminnairi profile image
Amin • Edited

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.

Collapse
 
hanachin profile image
Seiei Miyagi

ruby <3

def remove_question_marks(s)
  s |> delete ??
end
Collapse
 
serbuvlad profile image
Șerbu Vlad Gabriel

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);
Collapse
 
aminnairi profile image
Amin

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!

Collapse
 
georgecoldham profile image
George

Tomorrows challenge:

Write a random challenge generator!

Collapse
 
aminnairi profile image
Amin

Oh, sounds sexy. I love it! Haha.

Collapse
 
peter profile image
Peter Kim Frank

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

Collapse
 
georgecoldham profile image
George • Edited

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

Collapse
 
jay profile image
Jay

Rust

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

Playground

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

... 😐

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
Collapse
 
thepeoplesbourgeois profile image
Josh

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"
Collapse
 
idanarye profile image
Idan Arye
// 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?"));
    }
}
Collapse
 
brightone profile image
Oleksii Filonenko
private static final OpinionAboutJava opinionAboutJava = OpinionAboutJavaFactory.getOpinionAboutJava("ugh...");
Collapse
 
idanarye profile image
Idan Arye

NOOOO!!!

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

Collapse
 
gypsydave5 profile image
David Wickes

ENTERPRISE

Collapse
 
mellen profile image
Matt Ellen • Edited

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

Collapse
 
ben profile image
Ben Halpern

Ruby

def no_more_questions(string)
  string.gsub("?", "")
end
Collapse
 
gypsydave5 profile image
David Wickes • Edited

sed is overkill. Try tr:

echo "why not use tr?" | tr -d '?'
Collapse
 
choroba profile image
E. Choroba

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.

Collapse
 
roadirsh profile image
Roadirsh • Edited

PHP :

str_replace('?', '', $string) 
Collapse
 
aminnairi profile image
Amin

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.

Collapse
 
roadirsh profile image
Roadirsh

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

function myOwnStrReplaceBecauseIDontLikeSnakeCase($string) {
  return str_replace('?', '', $string);
}
Thread Thread
 
aminnairi profile image
Amin

That function name tho. haha!

Collapse
 
chrisachard profile image
Chris Achard

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("?", "")
Collapse
 
room_js profile image
JavaScript Room

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"
Collapse
 
gypsydave5 profile image
David Wickes

Try tr instead. 😁

 
hanachin profile image
Seiei Miyagi • Edited

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

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

puts s
Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell:

removeQuestionMarks :: String -> String
removeQuestionMarks = filter (/='?') 
Collapse
 
aminnairi profile image
Amin • Edited

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

removeQuestionMarks : String -> String
removeQuestionMarks = String.filter ((/=) '?')
Collapse
 
savagepixie profile image
SavagePixie
const questionToStatememt = str => str.replace(/\?+/g, '')
Collapse
 
kvharish profile image
K.V.Harish

My solution in js

const removeQuestionMark = (str) => str.replace(/\?/gi, '');
Collapse
 
jasman7799 profile image
Jarod Smith
const removeQuestionMarks = str => str.replace(/\?+/g,'');
Collapse
 
hanachin profile image
Seiei Miyagi

I love weird Ruby syntax😆

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

Collapse
 
stephanie profile image
Stephanie Handsteiner

PHP:

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

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.

 
room_js profile image
JavaScript Room

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

Collapse
 
willsmart profile image
willsmart • Edited

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

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

(bash on mac)

Collapse
 
vivek97 profile image
Vivek97 • Edited
System.out.println("??he?llo".replace("?", " "));


`

Collapse
 
matrossuch profile image
Mat-R-Such

Python

def remove_(text):  return text.replace('?','')

print(remove_('He?l?lo?'))
Collapse
 
ganesh profile image
Ganesh Raja

Python:

print(s.replace('?',''))
Collapse
 
hectorpascual profile image
Héctor Pascual

As simple as it sounds, in python :

lambda s : re.sub(r'\?','', s)