Sunday, February 13, 2011

Repeating characters in multiple languages

A friend of mine asked me how to repeat a string a specified number of times. There are a few times when ones wants to do this when programing. Here is the "repeating operator" in various languages. I tried to use an operator when possible - but in certain cases I used a function. In all cases I repeat a string followed by a newline.
The BSDs
for i in $(jot 1 5);
do echo -n "Hi";
done;
echo "";

Output:
HiHiHiHiHi
Most Linux distributions
for i in $(seq 1 1 5);
do echo -n "Hi";
done;
echo "";

Output:
HiHiHiHiHi
Perl
print "-" x 10;
print "\n"

Output:
----------
Python
"ab" * 10 Output: 'abababababababababab'
R
paste(rep("Hi",5), collapse='')
Output:
[1] HiHiHiHiHi
Ruby
print "-" * 10;
print "\n"

Output:
----------
Tcl
string repeat "Hi" 5
Output:
HiHiHiHiHi
ZSH
repeat 5 printf 'abc';
echo "";

Output:
abcabcabcabcabc
update 5/30/11: Thanks to Hans I found out that jot is not POSIX. Also fixed formatting.

No comments:

Post a Comment

Have something you want to say? You think I'm wrong? Found something I said useful?
Leave a comment!