1、通过下面这个实例掌握char和string的区别、字符串类型与普通引用类型在使用上的区别、字符串的比较方法等。
要点:C#中的字符类型为双字节类型,char为值类型、string为引用类型但又与普通引用类型在使用方法不一样。
namespace Demo_CharAndString
{
class Program
{
static void Main(string[] args)
{
Test t1 = new Test();
Test t2;
t2 = t1;
Console.WriteLine("t1.x={0},t1.y={1}",t1.x,t1.y);
Console.WriteLine("t2.x={0},t2.y={1}", t2.x, t2.y);
t1.x = 77;
t1.y = 88;
Console.WriteLine("t1.x={0},t1.y={1}", t1.x, t1.y);
Console.WriteLine("t2.x={0},t2.y={1}", t2.x, t2.y);
//StringBuilder
string name = "小宇飞刀";
char sex = '女';
double score = 80.5;
string str1 = name;
str1 = "xieyunc";//这一操作并不会改变name变量的值,why?
Console.WriteLine("name={0},sex={1},score={1}",name,sex,score);
Console.WriteLine("z:\\csharp_teach\babcd");
//Console.WriteLine("abcd");
string s1=null, s2="";
string str2;
str2 = s1 == s2 ? "相等" : "不相等";
Console.WriteLine("str2的值为:{0}", str2);
//if (s1 == null)
if (s2.Equals(string.Empty))
{
Console.WriteLine("条件为真");
}
str1 = "abc";
str2 = "Abc";
if (str1.ToLower() == str2.ToLower())
Console.WriteLine("相等");
else
Console.WriteLine("不相等");
if (string.Compare(str1,str2,true)==0)
Console.WriteLine("相等");
else
Console.WriteLine("不相等");
if (str1.ToLower().CompareTo(str2.ToLower())==0)
Console.WriteLine("相等");
else
Console.WriteLine("不相等");
Console.ReadKey();
}
}
class Test
{
public int x = 10;
public int y = 20;
}
}
2、string和DateTime类型的格式化。
a)设计一个简单的加法计算小程序用演示Console.WriteLine("格式化字符串",参数)的用法
b)列出DateTime类型中的各种格式化字符的用法:{0:d}、{0:D}、{0:g}、{0:G}……
3、string类型中的Substring()、Split()、Insert()、Remove()、Replace()、PadLeft()、PadRight()的用法
4、string与StringBuilder的差异
5、演示DEMO源代码在github上的仓库地址:
https://github.com/xieyunc/csharp_teach.git