user1998735
user1998735

Reputation: 253

Inserting user defined number of spaces before and after string using C#

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?

Upvotes: 6

Views: 318

Answers (6)

sujith karivelil
sujith karivelil

Reputation: 29016

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.

Upvotes: 4

Jim
Jim

Reputation: 2984

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;
}

Upvotes: 3

JohnG
JohnG

Reputation: 9469

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) + "<";
}

Upvotes: 1

Mohit S
Mohit S

Reputation: 14044

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);

Upvotes: 3

mybirthname
mybirthname

Reputation: 18127

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);

Upvotes: 3

clarkitect
clarkitect

Reputation: 1730

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

Upvotes: 3

Related Questions