Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I repeat a character n times in a string?

Tags:

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/; 
like image 651
chappar Avatar asked Mar 22 '09 08:03

chappar


People also ask

How do you repeat a string for n times?

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.

How do you make a string repeating characters?

Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);

How do you repeat a string 3 times in python?

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.

How do you do the repeat method?

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.


1 Answers

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; 
like image 53
kixx Avatar answered Sep 21 '22 13:09

kixx