Tuesday, March 15, 2011

Easy way to replicate/repeat string or characters

You may have come across a scenario to display some special character, like '*', in place of user's password in some control or displaying some repeated strings or characters like:

0000001
0000002
0000003
0000103

Here I will show two ways of doing so.
string sFiveZeros = new String('0', 5);
Console.WriteLine(sFiveZeros);
//Output: 00000


string sSevenStars = new String('*', 7);
Console.WriteLine(sSevenStars);
//Output: *******

Now the other way is a mix of string.Concat() and System.Collections.ArrayList.Repeat() methods.
string sRepeated123 = string.Concat(System.Collections.ArrayList.Repeat("123", 5).ToArray());
Console.WriteLine(sRepeated123);
//Output: 123123123123123


string sRepeatedAbc = string.Concat(System.Collections.ArrayList.Repeat("abc", 5).ToArray());
Console.WriteLine(sRepeatedAbc);
//Output: abcabcabcabcabc

No comments:

Post a Comment