I am learning Perl, so please bear with me for this noob question.
How do I repeat a character n times in a string?
I want to do something like below:
$numOfChar = 10; s/^\s*(.*)/' ' x $numOfChar$1/;
String Class repeat() Method in Java with Examples The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times.
Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);
To repeat a string in Python, We use the asterisk operator ” * ” The asterisk. is used to repeat a string n (number) of times. Which is given by the integer value ” n ” and creates a new string value. It uses two parameters for an operation: the integer value and the other is String.
JavaScript String repeat()The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.
By default, substitutions take a string as the part to substitute. To execute code in the substitution process you have to use the e
flag.
$numOfChar = 10; s/^(.*)/' ' x $numOfChar . $1/e;
This will add $numOfChar
space to the start of your text. To do it for every line in the text either use the -p
flag (for quick, one-line processing):
cat foo.txt | perl -p -e "$n = 10; s/^(.*)/' ' x $n . $1/e/" > bar.txt
or if it's a part of a larger script use the -g
and -m
flags (-g
for global, i.e. repeated substitution and -m
to make ^
match at the start of each line):
$n = 10; $text =~ s/^(.*)/' ' x $n . $1/mge;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With