5

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

prosseek
  • 155,475
  • 189
  • 518
  • 818

7 Answers7

5

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

string zeros = new String('0', 5);
Jay Riggs
  • 51,115
  • 9
  • 133
  • 146
5

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"
Jeff Mercado
  • 113,921
  • 25
  • 227
  • 248
4

To add to the other answers, you won't be able to use this string constructor with another string to repeat strings, such as string s = new string("O", 5);. This only works with chars.

However, you can use Enumerable.Repeat() after adding using System.Linq; to achieve the desired result with strings.

string s = string.Concat(Enumerable.Repeat("O", 5));
Scott
  • 989
  • 7
  • 13
  • There is no such constructor that repeats strings, only for characters. – Jeff Mercado Sep 17 '11 at 06:00
  • @Jeff Mercado That's what I said. – Scott Sep 17 '11 at 06:27
  • Ah oops, didn't notice you said that. It's better to leave out code that does not work so you don't confuse people like me to think you're suggesting it works or at the very least, format it so it doesn't appear as normal code. :) – Jeff Mercado Sep 17 '11 at 06:30
2

Use

 string s = new string( '0', 5 );

Found here

Ray Toal
  • 79,229
  • 13
  • 156
  • 215
0

Depending on your application, this may be useful too:

int n = 0;
string s = n.ToString().PadRight(5, '0');
bweaver
  • 143
  • 1
  • 11
0

Don't ever, ever use this: string.Join("0", new string[6]);

Why not just "00000" ?! ducks

longda
  • 9,445
  • 6
  • 44
  • 66
  • Anti-answers can be good if you can provide a better solution. That's definitely something you don't want to do but writing out the string literal might not always be feasible. – Jeff Mercado Sep 17 '11 at 05:56
0

This one only works with zero: 0.ToString("D5");

longda
  • 9,445
  • 6
  • 44
  • 66