Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's print "0"*5 equivalent in C#

Tags:

c#

printing

When I need to print "00000", I can use "0"*5 in python. Is there equivalent in C# without looping?

like image 723
prosseek Avatar asked Sep 17 '11 05:09

prosseek


2 Answers

Based on your example I figure you're going to be using these strings to help zero-pad some numbers. If that's the case, it would be easier to use the String.PadLeft() method to do your padding. You could be using the similar function in python as well, rjust().

e.g.,

var str = "5";
var padded = str.PadLeft(8, '0'); // pad the string to 8 characters, filling in '0's
// padded = "00000005"

Otherwise if you need a repeated sequence of strings, you'd want to use the String.Concat() method in conjunction with the Enumerable.Repeat() method. Using the string constructor only allows repetition of a single character.

e.g.,

var chr = '0';
var repeatedChr = new String(chr, 8);
// repeatedChr = "00000000";
var str = "ha";
// var repeatedStr = new String(str, 5); // error, no equivalent
var repeated = String.Concat(Enumerable.Repeat(str, 5));
// repeated = "hahahahaha"
like image 78
Jeff Mercado Avatar answered Oct 10 '22 03:10

Jeff Mercado


One of the String ctor overloads will do this for you:

string zeros = new String('0', 5);
like image 35
Jay Riggs Avatar answered Oct 10 '22 03:10

Jay Riggs