6

I am using string builder to format my string to append and prepend white spaces at the start and end of the string

here is what I have so far:

private void button1_Click(object sender, EventArgs e)
{
   String Word = textBox1.Text;
   AppendPrependText(Word);
}
private void AppendPrependText (String Word)
{
   int count = Convert.ToInt32(textBox2.Text);
   int WordCount = Word.Count();
   int totalChar = count + WordCount;
   string format = "{-"+totalChar+ "," +totalChar+ "}";
   StringBuilder sb = new StringBuilder();

   sb.AppendLine(string.Format(format, Word));
   textBox3.Text = sb.ToString();
}

but I'm getting the error incorrect format. What am i doing wrong?

2
  • could you please specify the sample input and expected output? Commented Nov 17, 2016 at 3:15
  • 2
    Why not use .PadLeft() and .PadRight()? Commented Nov 17, 2016 at 4:15

6 Answers 6

4

I think you need not to use separate operation for formatting the string, you can use .AppendFormat() method of the StringBuilder Class. Here is a sample code for you:

StringBuilder sbAppendFormat = new StringBuilder();
int numberOfSpaces=0;
if(int.TryParse(textBo2.Text, out numberOfSpaces))
{
    string whiteSpaceSequence= new string(' ',numberOfSpaces);
    sbAppendFormat.AppendFormat("{0}{1}{0}", whiteSpaceSequence, "This is your String");
}
textBox3.Text = sbAppendFormat.ToString();

Note:- Assume that you need to add Some white spaces(let it be 5) before and after the specific word.

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

4 Comments

Glad to hear that, and happy to help you
Awesome. :) This is beautiful and simple.
simplified: sbAppendFormat.AppendFormat("{0}{1}{0}", whiteSpaceSequence, "This is your String");
@matk: yep, nice suggestion
3

There's two issues here. The first is that you're correctly using a StringBuilder to format a string which reduces the overhead caused by concatenation but you're also performing extra concatenation on that format local variable.

The second issue is that your format string is wrong: it doesn't include the argument index. Your method expects a single word, so that index should be zero before the padding instruction.

Fortunately, you could skip past the concatenation of the format string and simply append your user-defined space (or whatever character) to the fresh instance of the StringBuilder

Comments

3

Your code has some errors:

Format Exception will be thrown by this line for sure:

sb.AppendLine(string.Format(format, Word));

Your current format doesn't contain any {0} in which the Word value should be replaced.

//you should put here somewhere {0} in the format or remove the Word for string.Format
//for an example
string format = "{-" + totalChar + "," + totalChar + "}{0}";

Also this line is possible Format Exception if the textBox2.Text is for an example a11:

int count = Convert.ToInt32(textBox2.Text);

You need to use int.TryParse

int count = 0;
int.TryParse(textBo2.Text, out count);

Comments

3

What seems to be the issue is

string format = "{-"+totalChar+ "," +totalChar+ "}";

Letz say if totalChar = 10; than

format = "{-10,10}"

which is not a valid format whereas it should be

{0,10}{1,10}

and thus your string would look like

Console.WriteLine(string.Format("{0,10}{1,10}", "Mohit",""));

The third argument was intentionally left blank so that nothing would be printed after the word. but you will have 10 spaces.

But I would recommend you to use String.PadRight and String.PadLeft instead.

An example to demostrate your task using PadLeft and PadRight

int count = 5;
string st = "mohit ";
int WordCount = st.Count();
int totalChar = count + WordCount;

st = st.PadRight(totalChar, ' ');
st = st.PadLeft(totalChar + count, ' ');
Console.WriteLine(st);

Comments

3

For simple adding spaces or chars, in front and/or back, Padding will work fine.

private void button1_Click(object sender, EventArgs e)    
{
    int amount;
    int.TryParse(textBox2.Text, out amount);

    var str = textBox1.Text.PadLeft(amount + textBox1.TextLength);
    str = str.PadRight(amount + str.Length);

    textBox3.Text = str;
}

Then you can choose a spacer (paddingChar) also later if needed/wanted

var str = textBox1.Text.PadLeft(amount + textBox1.TextLength, '>');
str = str.PadRight(amount + str.Length, '<');

Additionally with an extra method:

private void button1_Click(object sender, EventArgs e)    
{
    textBox3.Text = Format(textBox1.Text, textBox2.Text);
}

private string Format(string word, string spaces)
{
    int amount;
    int.TryParse(spaces, out amount);

    var str = word.PadLeft(amount + word.Length);
    str = str.PadRight(amount + str.Length);
    return str;
}

Comments

1

I did not use StringBuilder, I returned a String from AppendPrependText. The if statement checks for invalid integer input in textBox2, if its invalid return the original string. If it is a valid integer, create a padString with count number of spaces then return the original string sandwiched between two of the padStrings.

EDIT: added check for negative numbers by adding AND count > 0 to the if statement.

private String AppendPrependText(String Word)
{
  int count = 0;
  if (int.TryParse(textBox2.Text, out count) && count > 0)
  {
    String padString = "".PadLeft(count, ' ');
    return padString + Word.ToString() + padString;
  }
  else
  {
    return Word;
  }
}

private void button1_Click_1(object sender, EventArgs e)
{
  String Word = textBox1.Text;
  textBox3.Text = ">" + AppendPrependText(Word) + "<";
}

Comments

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.