简体   繁体   English

使用C#在字符串之前和之后插入用户定义的空格数

[英]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? 我究竟做错了什么?

I think you need not to use separate operation for formatting the string, you can use .AppendFormat() method of the StringBuilder Class . 我认为你不需要使用单独的操作来格式化字符串,你可以使用StringBuilder Class .AppendFormat()方法。 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. 注意: - 假设您需要在特定单词之前和之后添加一些空格(让它为5 )。

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. 第一个是你正确地使用StringBuilder来格式化字符串,这减少了由连接引起的开销,但是你也在那个format局部变量上执行额外的连接。

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 幸运的是,您可以跳过格式字符串的串联,只需将用户定义的空间(或任何字符)附加到StringBuilder的新实例上

Your code has some errors: 您的代码有一些错误:

Format Exception will be thrown by this line for sure: Format Exception下,此行将抛出Format Exception

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

Your current format doesn't contain any {0} in which the Word value should be replaced. 您当前的格式不包含应替换Word值的任何{0}

//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 : 如果textBox2.Text用于示例a11,则此行也可能是Format Exception

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

You need to use int.TryParse 您需要使用int.TryParse

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

What seems to be the issue is 似乎问题是什么

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

Letz say if totalChar = 10; Letz说如果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. 但你将有10个空格。

But I would recommend you to use String.PadRight and String.PadLeft instead. 但我建议你改用String.PadRightString.PadLeft

An example to demostrate your task using PadLeft and PadRight 使用PadLeft和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);

For simple adding spaces or chars, in front and/or back, Padding will work fine. 对于在前面和/或后面添加空格或字符的简单方法,Padding可以正常工作。

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 然后你可以在以后需要/想要的时候选择spacer (paddingChar)

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

I did not use StringBuilder , I returned a String from AppendPrependText . 我没有使用StringBuilder ,我从AppendPrependText返回了一个String The if statement checks for invalid integer input in textBox2, if its invalid return the original string. if语句检查textBox2中的无效整数输入,如果其无效则返回原始字符串。 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 . 如果它是一个有效的整数,请创建一个count为空格的padString ,然后返回夹在两个padStrings之间的原始字符串。

EDIT: added check for negative numbers by adding AND count > 0 to the if statement. 编辑:通过在if语句中添加AND count > 0来添加对负数的检查。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM