10

Is there a built-in function or more efficient way to add character to a string X number of times?

for example the following code will add '0' character 5 times to the string:

int count = 5;
char someChar = '0';
string myString = "SomeString";

for(int i=0;i<count;i++)
{
    myString = someChar + myString;
}
  • possible duplicate of [Is there a built-in function to repeat string or char in .net?](http://stackoverflow.com/questions/4115064/is-there-a-built-in-function-to-repeat-string-or-char-in-net) – Sajeetharan May 24 '14 at 14:35
  • @Sajeetharan in my case using `PadRight()` or `PadLeft()` is more efficient and does exactly what I need with minimal overhead. –  May 24 '14 at 14:45
  • possible duplicate of [Best way to repeat a character in C#](http://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp) – chue x May 25 '14 at 19:41

5 Answers5

9

Use PadLeft() or PadRight()

An example for PadRight():

int count = 5;
char someChar = '0';
string myString = "SomeString";

myString = myString.PadRight(count + myString.Length, someChar);

// output -> "SomeString00000"

Remember the first parameter of either method is the total string length required hence why I am adding count to the original string length.

Likewise if you want to append the character at the start of the string use PadLeft()

myString = myString.PadLeft(count + myString.Length, someChar);

// output -> "00000SomeString"
connectedsoftware
  • 6,987
  • 3
  • 28
  • 43
4
string.Concat(Enumerable.Repeat("0", 5));

will return

"00000"

Refered from :Is there a built-in function to repeat string or char in .net?

Community
  • 1
  • 1
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
3

You can also do it as:

string line = "abc";
line = "abc" + new String('X', 5);
//line == abcXXXXX
sshashank124
  • 31,495
  • 9
  • 67
  • 76
2

Take a look here, You can use PadRight() / PadLeft();

int count = 5;
char someChar = '0';
string myString = "SomeString";
var stringLength = myString.Length;

var newPaddedStringRight = myString.PadRight(stringLength  + count, '0'); 
//will give SomeString00000
var newPaddedStringLeft = myString.PadLeft(stringLength  + count, '0'); 
//will give 00000SomeString

Remember, a string is Immutable, so you'll need to assign the result to a new string.

Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
1

You could also use StringBuilder. As the string size increases the += incurs a cost on array copy.