字符串一旦被 创建就不能被 修改
举例:
string s1 = “Hello World!”;
var s2 = s1.ToUpper();
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.ReadKey();
string s1 = “abcd”;
string s2 = “a” + “b” + “c” + “d”;
Console.WriteLine(Object.ReferenceEquals(s1,s2));
Console.ReadKey();
s1 字符串常量加到字符串池中,
“a”,”b”,”c”,”d” 字符常量来取时,先到字符串池中取
发现有时,就直接从池中取。所以 s1,s2 是相同的对象
变量增加到字符串池
string s1 = “a”;
string s2 = “b”;
string s3 = s1 + s2;
string.Intern(s1);
string.IsInterned(s2);
Console.ReadKey();
为什么字符串类前要加sealed关键字
1, 子类如果继承字符串类以后可能会对字符串类进行修改,可能 会改变字符串的特性
2, CLR对字符串提供了各种特殊的操作方式,如果有很多类继承了字符串类,则CLR需要
对更多的类型提供特殊操作,这样可能会降低性能
//{ 0,[,number]}[:格式]
//[,number] 表示 宽度 + 对齐 , 正整数表示右对齐,负整数表示左对齐
// 不要货币符号
Console.WriteLine(“===姓名:{0,-10},薪资{1,20:f2}=”,“zs”,800.1234);
Console.ReadKey();
//StringComparison.OrdinalIgnoreCase
// char 转字符串
char[] chs = new char[] { ‘a’, ‘b’, ‘c’ };
string s = new string(chs);
Console.WriteLine(s);
string msgs = “abcdef hello”;
msgs = msgs.Substring(7,5);
Console.WriteLine(msgs);
Console.ReadKey();
练习:得到文件名
string path = @“D:\BaiduNetdiskDownload\filename.txt”;
path = path.Substring(path.LastIndexOf(@“”) + 1);
Console.WriteLine(path);
Console.ReadKey();
得到字符串中的IP,port
string mes = “192.168.11.233[port=21,type=ftp]”;
string[] parts = mes.Split(new string[] {
“[port=”,“,type=”,“]”},StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(“IP:{0}”,parts[0]);
Console.WriteLine(“port:{0}”, parts[1]);
Console.WriteLine(“server:{0}”,parts.Length>2?parts[2]:“”);
Console.ReadKey();
string[] lines = File.ReadAllLines(@“D:\size.txt”, Encoding.Default);
string msg = string.Empty;
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < lines.Length; i++)
{
msg = msg + lines[i];
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
Console.WriteLine(“ok”);
Console.ReadKey();
string[] lines = File.ReadAllLines(@“D:\size.txt”, Encoding.Default);
StringBuilder stringBuilder = new StringBuilder();
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < lines.Length; i++)
{
stringBuilder.Append(lines[i]);
}
watch.Stop();
Console.WriteLine(watch.Elapsed);
Console.WriteLine(“ok”);
Console.ReadKey();
Person p = new Person();
WeakReference wr = new WeakReference§;
Console.WriteLine(“开始”);
p = null;
Console.WriteLine(“引用中。。。”);
重新使用p对象
//if (wr.IsAlive)
//{
// object o = wr.Target;
// if (o != null)
// {
// Person p1 = o as Person;
// // 就可以使用Person 对象了, 这个对象还是之前的对象
// }
//}
object o = wr.Target;
if (o != null)
{
Person p1 = o as Person;
// 就可以使用Person 对象了, 这个对象还是之前的对象
p1.Name = “张三”;
p = p1;
}
Console.WriteLine(“执行完成了”);
Console.WriteLine(p.Name);
Console.ReadKey();
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}