user1998735 user1998735 - 3 months ago 21
C# Question

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


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}{2}", whiteSpaceSequence, "This is your String", whiteSpaceSequence);
textBox3.Text = sbAppendFormat.ToString();

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