0

I'm trying to make a simple tab space between words, using a dynamic ammount. How would I do this?

Simply like this:

string p1 = keysC[pos]+"="+valsC[pos];
int tabs = (60 - p1.Length) / 4;
wr.WriteLine(p1 + ("\t" * tabs) +"//"+comsC[pos]);
2
  • what are you asking for ? What doesn't work ? What is the expected result ? Is this a question or an answer ? Commented Jan 13, 2014 at 22:33
  • Side note: not everyone have tabs set to 4 (I believe in most cases default is actually 8). Consider instead padding with spaces (almost same code, but will display properly in more cases). Commented Jan 13, 2014 at 22:48

4 Answers 4

5

The String contructor has an overload for that.

string p1 = keysC[pos]+"="+valsC[pos];
int tabs = (60 - p1.Length) / 4;
wr.WriteLine(p1 + new string('\t', tabs) +"//"+comsC[pos]);

Note that the first argument of the constructor is a char and not a string.

Sign up to request clarification or add additional context in comments.

Comments

4

You can use the string constructor:

string allTabs = new string('\t', tabs);

Comments

3

Try this:

string spacing = new String('\t', tabs);

Comments

2

Sounds like just need to write a function that repeats the same string N number of times

static string RepeatString(string source, int times) { 
  var builder = new StringBuilder(source.Length * times);
  for (int i = 0; i < times; i++) {
    builder.Append(source);
  }
  return builder.ToString();
}

Note that if you only care about repeating a char like \t then use @Vache's answer of new string(theChar, theCount)

3 Comments

+1. Or even String.Join(null, Enumerable.Repeat(source, times));
@AlexeiLevenkov: which would be less efficient than the constructor.
@TimSchmelter - indeed for of single character as in actual OP's case one should use constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.