目录
????????符串是不可改变的对象,字符串在创建以后,就不会被改变,当使用字符串对象的Replace、split或Remove等方法操作字符串时,实际上是产生了一个新的字符串对象,原有的字符串如果没有被引用,将会被垃圾收集器回收。如果频繁地使用字符串中的方法对字符串进行操作,会产生大量的没有被引用的字符串对象,这会增加垃圾收集的压力,造成系统资源的浪费。
????????因为使用StringBuilder操作字符串不会产生新的字符串对象,在使用StringBuilder对象前首先要引用命名空间System.Text。
????????由于字符串的不可变性,使用StringBuilder操作字符串无疑是非常方便和有效的方法。StringBuilder对象的使用方法:
StringBuilder P_stringbuilder =?new?StringBuilder("abc");??//使用new关键字调用构造方法创建对象
P_stringbuilder.Insert(2,Environment.NewLine); ? //调用对象的Insert方法向字符串中插入字符
????????建立StringBuilder对象后,可以调用操作字符串的方法,从而方便操作字符串对象适当地使用StringBuilder操作字符串,会使程序运行更加高效。
//按标点符号对字符串分行显示
using System.Text;
namespace _039
{
public partial class Form1 : Form
{
private GroupBox? groupBox1;
private TextBox? textBox3;
private Button? button1;
private TextBox? textBox1;
private TextBox? textBox2;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// textBox3
//
textBox3 = new TextBox
{
Location = new Point(12, 22),
Multiline = true,
Name = "textBox3",
Size = new Size(310, 46),
TabIndex = 6,
Text = "在下面文本框中输入字符串,并使用(,)号分隔,点击分行显示按钮,根据(,)号对字符串进行分行。"
};
//
// button1
//
button1 = new Button
{
Location = new Point(130, 170),
Name = "button1",
Size = new Size(75, 23),
TabIndex = 3,
Text = "分行显示",
UseVisualStyleBackColor = true
};
button1.Click += Button1_Click;
//
// textBox1
//
textBox1 = new TextBox
{
Location = new Point(12, 80),
Multiline = true,
Name = "textBox1",
Size = new Size(310, 84),
TabIndex = 4
};
//
// textBox2
//
textBox2 = new TextBox
{
Location = new Point(12, 200),
Multiline = true,
Name = "textBox2",
Size = new Size(310, 84),
TabIndex = 5
};
//
// groupBox1
//
groupBox1 = new GroupBox
{
Location = new Point(0, 0),
Name = "groupBox1",
Size = new Size(334, 74),
TabIndex = 0,
TabStop = false,
Text = "操作说明:"
};
groupBox1.Controls.Add(textBox3);
groupBox1.SuspendLayout();
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(334, 296);
Controls.Add(textBox2);
Controls.Add(textBox1);
Controls.Add(button1);
Controls.Add(groupBox1);
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "按标点符号对字符串分行";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
}
private void Button1_Click(object? sender, EventArgs e)
{
StringBuilder stringbuilder = new(textBox1!.Text); //创建字符串处理对象
for (int i = 0; i < stringbuilder.Length; i++)
if (stringbuilder[i] == ',') //判断是否出现(,)号
stringbuilder.Insert(++i, Environment.NewLine); //向字符串内添加换行符
textBox2!.Text = stringbuilder.ToString(); //得到分行后的字符串
}
}
}
?