我有 Windows 窗体项目。表单上有一个文本框,名为 txt。任务是在文本框中写入用户的字符串,分两列解析文本。每列必须左对齐。这是示例:
--------------------------
Parameters Values
height 36
width 72
length of trousers 32
--------------------------
每个值都必须在另一个之下。显然,我们需要一种方法,在每个参数后输入必要数量的空格。我开发了这种方法:
private string AddSpaces(string str)
{
const int MAX_WIDTH = 50;
// We've got a 50 symbols field to fill it with current parameter
// name and add necessary number of spaces.
StringBuilder strWithSpaces = new StringBuilder();
int numOfSpaces = MAX_WIDTH - str.Length;
for (int i = 0; i < numOfSpaces; i++)
{
strWithSpaces.Append(" ");
}
return strWithSpaces.ToString();
}
我已经使用以下字符串测试了此方法:
string report = Environment.NewLine + "-------------" + DateTime.Now +
"-------------" + Environment.NewLine +
"Вихідні дані:" + Environment.NewLine +
"a:" +
AddSpaces("a:") +
"1" +
Environment.NewLine +
"ab:" +
AddSpaces("ab:") +
"1" +
Environment.NewLine +
"abcdefg:"+
AddSpaces("abcdefg:") +
"1" +
Environment.NewLine;
并且制作完成后
txt.Text += report;
我有一张意想不到的照片:
之后,我尝试将测试字符串写入文件。结果如下:
文件中的输出是正确的。文本框中的输出是错误的。文本框有问题。如何解决这个问题?这是我的测试项目的代码:
/*
Correct output looks like this:
a: 1
ab: 1
abcdefg: 1
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace spaces
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string report = Environment.NewLine + "-------------" + DateTime.Now +
"-------------" + Environment.NewLine +
"Вихідні дані:" + Environment.NewLine +
"a:" +
AddSpaces("a:") +
"1" +
Environment.NewLine +
"ab:" +
AddSpaces("ab:") +
"1" +
Environment.NewLine +
"abcdefg:" +
AddSpaces("abcdefg:") +
"1" +
Environment.NewLine;
txt.Text += report;
using (StreamWriter outfile =
new StreamWriter(@"D:\test.txt"))
{
outfile.Write(report);
}
}
private string AddSpaces(string str)
{
const int MAX_WIDTH = 50;
StringBuilder strWithSpaces = new StringBuilder();
int numOfSpaces = MAX_WIDTH - str.Length;
for (int i = 0; i < numOfSpaces; i++)
{
strWithSpaces.Append(" ");
}
return strWithSpaces.ToString();
}
}
}