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

标签 c# .net string textbox string-formatting

我正在使用字符串生成器来格式化我的字符串以在字符串的开头和结尾附加和前置空格

这是我目前所拥有的:

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

但我收到错误格式不正确。我做错了什么?

最佳答案

我认为您不需要使用单独的操作来格式化字符串,您可以使用StringBuilder 类.AppendFormat() 方法。这是一个示例代码:

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

注意:- 假设您需要在特定单词前后添加一些空格(让它是 5)。

关于c# - 使用 C# 在字符串前后插入用户定义的空格数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40646078/

相关文章:

c++ - 如何将 utf32 字符串转换为 Unicode 字符串

c# - System.Guid 到 _GUID?

c# - 从 C# 类库生成文档

c# - 由于软件包不兼容,添加迁移失败

.net - app.config 中键的命名约定

php - 在 Python 中进行多个字符串替换的最快实现

c# - 合并键值对列表

c# - C#中一个简单线程池的代码

asp.net - 是否可以在 Visual Studio 2010 中调用 SSRS 2008 R2 报告?

c++ - 如何复制/设置 volatile std::string?