-1

How can I add space before a string with loop? Something like this:

string someString = "a";
for (int i = 0; i<5 ; i++)
{
   //add space before string code
}

Here is the logic I want:

//   int i = 0;
//   a;

//   int i = 1;
//   "\t" + a;

//   int i = 2;
//   "\t\t" + a;
  • 2
    is this a school assignment, in which you are required to use a loop? there are easier ways to achieve this (like string.PadLeft) actually – VT Chiew May 02 '19 at 08:38
  • Possible duplicate of [Best way to repeat a character in C#](https://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp) – xdtTransform May 02 '19 at 08:45
  • no it does not have to use loop what is the easiest way of doing it? @VT Chiew – 123john123 May 02 '19 at 08:54
  • Do you want spaces or tabs? Becuase in the 'logic you want' the char `\t` is a tab. – Dave May 02 '19 at 10:06

6 Answers6

2

Use this overload the string constructor:

int i = 5;
string result = new string('\t', i) + someString;

Since string is a immutable type, you create a new string each iteration which is pretty expensive. Because of that I would avoid the loop approach.

fubo
  • 44,811
  • 17
  • 103
  • 137
2
string spaceString = string.Empty;
for (int i = 0; i < 5; i++)
{
  spaceString += " ";
}

someString = spaceString + someString;
Dave
  • 1,912
  • 4
  • 16
  • 34
Shad
  • 1,185
  • 1
  • 12
  • 27
0

you can use string format like that:

string tab = "";
string someString = a;
for (int i = 0; i<5 ; i++)
{
   //add space before string code
   tab += "\t";
   string.Format("{0}{1}", tab, someString);
}
Leon
  • 443
  • 5
  • 19
0
string somestring = a;
    for (int i = 0; i<5 ; i++)
    {
       string result = "";
       for(int j = 0; j<i ; j++)
       {
         result+= "\t";
       }
       result+= somestring;
    }
JustasG
  • 31
  • 5
0
string someString = "a";
string result = "";
for (int i = 0; i < 6; i++)
{
    result = new string('\t', i) + someString;
    Console.WriteLine(result);
}
Console.ReadKey();
0

As john indicated in the comment that you do not need to use a loop, this is the ideal way:

int i = 5;
string s = "x";

string result = s.PadLeft(i + s.Length,'\t');
VT Chiew
  • 663
  • 5
  • 19