string类和StringBuilder格式化的使用

/*
string类和StringBuilder格式化的使用
*/
using System;
using System.Text;

namespace Frank
{
	public class Test
    {
		//程序入口
        public static void Main(string[] args)
        {
			//string类是一个不可变的类,如果对一个string类型的变量进行多少的修改应该使用StringBuilder类,因为后者比前者速度更快,更节省空间
			string str = "1";
			str += "2";
			StringBuilder SB = new StringBuilder();//可以设置默认大小等一些参数
			SB.Append("1");
			SB.AppendFormat("123{0}",4);
			Console.WriteLine(str+"\n"+SB.ToString());
			/*结果:
			12
			11234
			*/
			Test2 t2 = new Test2();
			t2.x = 10;
			t2.y = 20;
			t2.z = 30;
			Console.WriteLine("{0,10:N}",t2);//|| 1400 ||
        }
	}
	public struct Test2 : IFormattable//自定义结构体,然后自定义输出格式
	{
		public double x,y,z;
		public string ToString(string format,IFormatProvider formatProvider)
		{
			if(format == null)
			{
				return ToString();
			}
			string formatUpper = format.ToUpper();
			switch(formatUpper)
			{
				case "N":
				{
					return "|| "+ Norm().ToString()+" ||";
				}
				case "J":
				{
					return string.Format("{0:E}, {1:E}, {2:E}",x,y,z);
				}
				default:
					return ToString();
			}
		}
		public override string ToString()
		{
			return x + ", " + y + ", " + z;
		}
		public double Norm()
		{
			return x*x+y*y+z*z;
		}
	}
}

  

posted on 2013-11-30 15:02  wp456  阅读(791)  评论(0)    收藏  举报

导航