Double Space
April 4, 2017
Today’s exercise is simple, but some languages make it hard:
Write a program that returns an input string with each space character in the string doubled. For instance, the string “hello hello” (with one space between the two words) is transformed to “hello hello” (with two spaces between the two words).
That may not come out right in all browsers; here is the transformation again, with space characters replaced by plus signs for visibility, using a constant-space font:
"hello+hello" => "hello++hello"
Depending on your language, that might be an easy task, or a hard one. You may have to deal with memory allocation, or non-mutable strings, or appends that blow up to quadratic time.
Your task is to write a program that doubles the space characters in its input. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
As a perl programmer this one is trivial:
if you don’t want to use s{} could do
Clojure:
Also not too difficult in Python.
javascript:
function double_space(txt){
return txt.replace(/ /g,’ ‘);
}
https://pastebin.com/embed_js/MQchRuyU
Read-write Scheme.
Read-write Python.
Took the Python generator approach. We can feed the double_space generator with characters and they get doubled up.
MUMPS:
r !,word,! f i=1:1:$l(word,” “) w:i>1 ” ” w $p(word,” “,i)
hello, world!
hello, world!
A Haskell version. (Note: cat -e prints a ‘$’ at the end of a line.)
Nothing difficult for Ruby
`def double_space(string)
return string.gsub(/\s/, ‘ ‘)
end
puts double_space(“hello word”)`
for non streaming algorithms the former maybe slow and memory expensive then, we can use ByteStrings (lazy or strict, depends)
[…] how easy your favorite programming language makes it to work with strings. The problem is to double every blank in a string. That’s pretty simple but some languages make you deal with string allocation or perhaps, in […]
Powershell makes it easy:
Function Set-DoubleSpace ($a) {$a-replace” “,” “}
or from STDIN
(read-host)-replace” “,” “
in Java:
public String doubleSpaces(String in) {
return in.replace(” “, ” “);
}