在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
但如果性能的优劣很重要,则应该总是使用 StringBuilder 类来串联字符串。下面的代码使用 StringBuilder 类的 Append 方法来串联字符串,因此不会有 + 运算符的链接作用产生。 class StringBuilderTest { static void Main() { string text = null; // Use StringBuilder for concatenation in tight loops. System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < 100; i++) { sb.AppendLine(i.ToString()); } System.Console.WriteLine(sb.ToString()); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } 输出: 0 1 2 3 4 ... 在 .NET Framework 中使用 StringBuilder 类 实例化 StringBuilder 对象 StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); 设置容量和长度 StringBuilder MyStringBuilder = new StringBuilder("Hello World!", 25); 另外,可以使用读/写 Capacity 属性来设置对象的最大长度。下面的示例使用 Capacity 属性来定义对象的最大长度。 MyStringBuilder.Capacity = 25; EnsureCapacity 方法可用来检查当前 StringBuilder 的容量。如果容量大于传递的值,则不进行任何更改;但是,如果容量小于传递的值,则会更改当前的容量以使其与传递的值匹配。 修改 StringBuilder 字符串 1.Append StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); MyStringBuilder.Append(" What a beautiful day."); Console.WriteLine(MyStringBuilder); 输出: Hello World! What a beautiful day. 2.AppendFormat int MyInt = 25; StringBuilder MyStringBuilder = new StringBuilder("Your total is "); MyStringBuilder.AppendFormat("{0:C} ", MyInt); Console.WriteLine(MyStringBuilder); 输出: Your total is $25.00 3.Insert StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); MyStringBuilder.Insert(6,"Beautiful "); Console.WriteLine(MyStringBuilder); 输出: Hello Beautiful World! 4.移除 StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); MyStringBuilder.Remove(5,7); Console.WriteLine(MyStringBuilder); 输出: Hello 5.Replace StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); MyStringBuilder.Replace('!', '?'); Console.WriteLine(MyStringBuilder); 输出: Hello World? 将 StringBuilder 对象转换为 String using System; using System.Text; public class Example { public static void Main() { StringBuilder sb = new StringBuilder(); bool flag = true; string[] spellings = { "recieve", "receeve", "receive" }; sb.AppendFormat("Which of the following spellings is {0}:", flag); sb.AppendLine(); for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++) { sb.AppendFormat(" {0}. {1}", ctr, spellings[ctr]); sb.AppendLine(); } sb.AppendLine(); Console.WriteLine(sb.ToString()); } } 输出: Which of the following spellings is True: 0. recieve 1. receeve 2. receive |
请发表评论