zoukankan      html  css  js  c++  java
  • string类型的解释与方法

    
    

    基本概念

    
    

    string(严格来说应该是System.String) 类型是我们日常coding中用的最多的类型之一。那什么是String呢?^ ~ ^

    
    

    String是一个不可变的连续16位的Unicode代码值的集合,它直接派生自System.Object类型。

    
    

    与之对应的还有一个不常用的安全字符串类型System.Security.SecureString,它会在非托管的内存上分配,以便避开GC的黑手。主要用于安全性特高的场景。[具体可查看msdn这里不展开讨论了。=>msdn查看详情

    
    

    特性

    
    
    1. 由于String类型直接派生于Object,所以它是引用类型,那就意味着String对象的实例总是存在于堆上。
    2. String具有不变性,也就是说一旦初始化,它的值将永远不变。
    3. String类型是封闭的,换言之,你的任何类型不能继承String。
    4. 定义字符串实例的关键字string只是System.String 类型的一个映射。

    注意事项

    
    
    1. 关于字符串中的回车符和换行符一般大家喜欢直接硬编码‘ ’,但是不建议这么做,一旦程序迁移到其他平台,将出现错误。相反,推荐使用System.Environment类的NewLine属性来生成回车符和换行符,可以跨平台使用的。
    2. 常量字符串的拼接和非常量字符串在CLR中行为是不一样的。具体请查看性能部分。

    3. 字符串之前加@符号会改变编译器的行为,如果加了@符号,编译器会把String中的转义字符视为正常字符来显示。也就是我定义的什么内容就是什么内容,主要在使用文件路径或者目录字符串中使用。以下两个String内容的输出将完全一致。
    
    
            static void Main(string[] args)
                {
                    string a = "c:\temp\1";
                    string b = @"c:	emp1";
                    Console.WriteLine(a);
                    Console.WriteLine(b);
                    Console.Read();           
                }  
    
    

    性能

    
    
    1. c#的编译器直接支持String类型,并将定义的常量字符串在编译期直接存放到模块的元数据中。然后会在运行时直接加载。这也说明String类型的常量在运行时是有特殊待遇的。
    2. 由于字符串的不变性,也就意味着多个线程同时操作该字符串不会有任何线程安全的问题。这在某些共享配置的设计中很有用。
    3. 如果程序经常会对比重复度比较高的字符串,这会造成性能上的影响,因为对比字符串是要经过几个步骤的。为此CLR引入了一个字符串重用的技术,学名叫做‘字符串留用’。原理就是:CLR会在初始化的时候创建一个内部的哈希表,key是字符串,value就是留用字符串在托管堆上的引用。
      String类型提供了两个静态方法来操作这个哈希表:
    
    

    String.Intern

    
    

    String.IsInterned

    
    

    具体请查看msdn(https://msdn.microsoft.com/zh-cn/library/system.string.isinterned(v=vs.110).aspx)
    但是c#编译器默认是不开启字符串留用功能的,因为如果程序大量把字符串留用,应用程序总体性能可能会变得更慢。(微软也是挺纠结的,程序员TMD的更纠结)

    
    
    1. 如果我们的程序中有很多个一模一样值的常量字符串, c#的编译器会在编译期间把这些字符串合并为一个并写入模块的元数据中,然后修改所有引用该字符串的代码。这也是一种字符串重用技术,学名‘字符串池’。这意味着什么呢?这意味着所有值相同的常量字符串其实引用的是同一个内存地址的实例,在相同值非常多的情况下能显著提高性能和节省大量内存。
    
    
    string s1 = "hello 大菜";
    string s2 = "hello 大菜";
    unsafe
    {
       fixed (char* p = s1)
       {
           Console.WriteLine("字符串地址= 0x{0:x}", (int)p);
    
       }
       fixed (char* p = s2)
       {
           Console.WriteLine("字符串地址= 0x{0:x}", (int)p);
    
       }
    } 
    
    

    输出结果:

    
    
    字符串地址= 0x80002d84
    字符串地址= 0x80002d84
    
    

    可见实例的值只分配了一次,但是有一点需要说明,字符串仅用于编译期能确定值的字符串,也就是常量字符串。如果我的程序修改为:

    
    
    args = new string[] { "dfasfdsa"};
    string s1 = "hello 大菜"+ args[0];
    string s2 = "hello 大菜"+args[0];
    unsafe
    {
        fixed (char* p = s1)
        {
            Console.WriteLine("字符串地址= 0x{0:x}", (int)p);
    
        }
        fixed (char* p = s2)
        {
            Console.WriteLine("字符串地址= 0x{0:x}", (int)p);
    
        }
    }
    
    

    运行结果:

    
    
    字符串地址= 0x2e3c
    字符串地址= 0x2e7c
    
    
    1. 平时coding避免不了字符串的连接,如果一个频繁拼接字符串的场景下使用‘+’,对程序整体性能和GC影响还是挺大的,为此c#推出了 StringBuilder类型来优化字符串的拼接。相对于String类型的不变性来说,StringBuilder更像是可变的字符串类型。它的底层数据结构是一个Char的数组。另外还有容量(默认为16),最大容量(默认为int.MaxValue)等属性。StringBuilder的优势在于字符总数未超过‘容量’的时候,底层数组不会重新分配,这和String每次都重新分配形成最大的对比。如果字符总数超过‘容量’,StringBuilder会自动倍增容量属性,用一个新的数组来容纳原来的值,原来数组将会被GC回收。可见如果StringBuilder频繁的动态扩容也会损害性能,但是影响可能会比String小的多。 合理的设置StringBuilder初始容量对程序有很大帮助。测试如下:
    
    
    int count = 100000;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    string s = "";
    for (int i = 0; i < count; i++)
        {
            s += i.ToString();
        }
    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds);
    
    

    运行结果:

    
    
    14221
    
    

    查看GC的情况

    
    

    
    

    Gc执行的是如此频繁。 性能是可想而知的。接着看一下StringBuilder

    
    
    int count = 100000;
    Stopwatch sw = new Stopwatch();
    sw.Start();            
    StringBuilder sb = new StringBuilder();//听说程序员都这样命名StringBuilder
    for (int i = 0; i < count; i++)
     {
        sb.Append(i.ToString());
    }
    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds);
    
    

    运行结果:

    
    
    12
    
    

    GC情况:

    
    

    几乎没有GC(可能还未达到触发GC的临界点),如果我合理初始化了StringBuilder 容量,生产环境中结果差距将会更大。 呵呵 ^ ~ ^

    
    

    其他

    
    

    关于字符串留用和字符串池

    
    
    1. 一个程序集加载的时候,CLR默认会留用该程序集元数据中描述的所有文本常量字符串。由于可能会出现额外的哈希表查找造成的性能下降的现象,所以现在可以禁用这个特性了。
    2. coding中我们平常比较两个字符串是否相等,那这个过程是怎么样的呢?
      1. 首先判断字符的数量是否相等。
      2. CLR逐个对比字符最终确定是否相等。
    
    

    这个场景是适合字符串留用的。因为不再需要经过以上的两个步骤,直接哈希表拿到value就可以对比确定了。

    
    

    关于字符串拼接性能

    
    

    基于以上所有知识,那是不是StringBuilder拼接字符串性能永远都高于符号‘+’呢?答案是否定的。

    
    
     static void Main(string[] args)
            {
                int count = 10000000;
                Stopwatch sw = new Stopwatch();
                sw.Start();            
                string str1 = "str1", str2 = "str2", str3 = "str3";
                for (int i = 0; i < count; i++)
                {
                    string s = str1 + str2 + str3;
                }
                sw.Stop();
                Console.WriteLine($@"+用时: {sw.ElapsedMilliseconds}" );
    
                sw.Reset();
                sw.Start();
                for (int i = 0; i < count; i++)
                {
                    StringBuilder sb = new StringBuilder();//听说程序员都这样命名StringBuilder
                    sb.Append(str1).Append(str2).Append(str3);
                }
                sw.Stop();
                Console.WriteLine($@"StringBuilder.Append 用时: {sw.ElapsedMilliseconds}");
    
                Console.Read();
            }
    
    

    运行结果:

    
    
    +用时: 553
    StringBuilder.Append 用时: 975
    
    

    符号‘+’最终会调用String.Concat方法,当同时连接几个字符串时,并不是每连接一个都分配一次内存,而是把几个字符都作为 String.Concat方法的参数,只分配一次内存。所以在拼接的字符串个数比较少的场景下,String.Concat 性能是略高于StringBuilder.Append。string.Format 方法最终调用的是StringBuilder,这里不做展开讨论了,请自行参考其他文档。



    1
    .Replace(替换字符): public string Replace(char oldChar,char newChar);在对象中寻找oldChar,如果寻找到,就用newChar将oldChar替换掉。 如: string st = "abcdef"; string newstring = st.Replace('a', 'x'); Console.WriteLine(newstring); //即:xbcdef public string Replace(string oldString,string newString);在对象中寻找oldString,如果寻找到,就用newString将oldString替换掉。 如: string st = "abcdef"; string newstring = st.Replace("abc", "xyz"); Console.WriteLine(newstring); //即:xyzdef 2.Remove(删除字符): public string Remove(int startIndex);从startIndex位置开始,删除此位置后所有的字符(包括当前位置所指定的字符)。 如: string st = "abcdef"; string newstring = st.Remove(4); Console.WriteLine(newstring); //即:abcd public string Remove(int startIndex,int count);从startIndex位置开始,删除count个字符。 如: string st = "abcdef"; string newstring = st.Remove(41); Console.WriteLine(newstring); //即:abcdf 3.Substring(字符串提取): public string Substring(int startIndex);从startIndex位置开始,提取此位置后所有的字符(包括当前位置所指定的字符)。 如: string st = "abcdef"; string newstring = st.Substring(2); Console.WriteLine(newstring); //即:cdef public string Substring(int startIndex,int count);从startIndex位置开始,提取count个字符。 如: string st = "abcdef"; string newstring = st.Substring(22); Console.WriteLine(newstring); //即:cd 4.Trim(清空空格): public string Trim ():将字符串对象包含的字符串两边的空格去掉后返回。 public string Trim ( params char[] trimChars ):从此实例的开始和末尾移除数组中指定的一组字符的所有匹配项。 如: string st ="abcdef"; string newstring = st.Trim(new char[] {'a'});//寻找st字符串中开始与末尾是否有与'a'匹配,如有,将其移除。 Console.WriteLine(newstring); //即:bcdef 注:如果字符串为"aaaabcdef",返回依然为bcdef。当移除第一个a时,开始依然为a,继续移除,直到没有。 public string TrimEnd ( params char[] trimChars ):对此实例末尾与指定字符进行匹配,true则移除 public string TrimStart ( params char[] trimChars ):对此实例开始与指定字符进行匹配,true则移除 5.ToLower(转换大小写) public string ToLower():将字符串对象包含的字符串中的大写全部转换为小写。 6.IndexOf(获取指定的字符串的开始索引) public int IndexOf (sring field):在此实例中寻找field,如果寻找到,返回开始索引,反之,返回-1。 如: string st = "abcdef"; int num=st.IndexOf("bcd"); Console.WriteLine(num); //即:1 7.Equals(是否相等) public bool Equals (string value):比较调用方法的字符串对象包含字符串和参数给出的对象是否相同,如相同,就返回true,反之,返回false。 如: string a = "abcdef"; bool b = a.Equals("bcdef"); Console.WriteLine(b);//即:false public bool Equals ( string value, StringComparison comparisonType ):比较调用方法的字符串对象包含字符串和参数给出的对象是否在不区分大小写的情况下相同,如相同,就返回true,反之,返回false,第二个参数将指定区域性、大小写以及比较所用的排序规则. 如: string a = "ABCDEF"; bool b = a.Equals("abcdef",StringComparison.CurrentCultureIgnoreCase); Console.WriteLine(b);//即:true 8.Split(拆分) public string[] Split ( params char[] separator ):根据separator 指定的没有字符分隔此实例中子字符串成为Unicode字符数组, separator可以是不包含分隔符的空数组或空引用。 public string[] Split ( char[] separator, int count ):参数count 指定要返回的子字符串的最大数量。 如: string st = "语文|数学|英语|物理"; string[] split = st.Split(new char[]{'|'},2); for (int i = 0; i < split.Length; i++) { Console.WriteLine(split[i]); } 注:count不填则全部拆分 public enum StringSplitOptions 成员名称 说明 None 返回值包括含有空字符串的数组元素 RemoveEmptyEntries 返回值不包括含有空字符串的数组元素 如: string st = "语文|数学||英语|物理"; string[] split = st.Split(new char[]{'|'},StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < split.Length; i++) { Console.WriteLine(split[i]); } 将StringSplitOptions枚举和Split()方法联系起来: 1. public string[] Split ( char[] separator, StringSplitOptions options ):options指定StringSplitOptions枚举的RemoveEmptyEntries以省略返回的数组中的空数组元素,或指定StringSplitOptions枚举的None以包含返回的数组中的空数组元 2. public string[] Split ( char[] separator, int count, StringSplitOptions options ) 3. public string[] Split ( string[] separator, StringSplitOptions options ) 4. public string[] Split ( string[] separator, int count, StringSplitOptions options ) 9.Contains(判断是否存在) public bool Contains(string text):如果字符串中出现text,则返回true,反之false,如果text为("")也返回true。 如: string st="语文数学英语"; bool b=st.Contains("语文"); Console.WriteLine(b);//true 10.EndsWith,StartsWith(判断字符串的开始或结束) public bool EndsWith ( string value ):判断对象包含字符串是否以value指定的字符串结束,是则为 true;否则为 falsepublic bool EndsWith ( string value, StringComparison comparisonType ):第二个参数设置比较时区域、大小写和排序规则。 public bool StartsWith ( string value ):判断对象包含字符串是否以value指定的字符串开始,是则为 true;否则为 falsepublic bool StartsWith ( string value, StringComparison comparisonType ) :第二个参数设置比较时区域、大小写和排序规则。 如: string st="语文数学英语abc"; bool b=st.EndsWith("英语ABC",StringComparison.CurrentCultureIgnoreCase);//第二个参数忽略大小比较。 Console.WriteLine(b);//true 11.Insert(字符串插入) public string Insert ( int startIndex, string value ):在指定的字符串下标为startIndex前插入字符串value。返回插入后的值。
  • 相关阅读:
    Unity HDRP BentNormal的理解
    c语言变长数组VLA的变通实现
    中间件目录索引:redis,git,grpc等
    MYSQL插入脚本
    Polly是一个.NET弹性和瞬态故障处理库
    grpc的.net core使用
    基于PaddleOCR实现AI发票识别的Asp.net Core应用
    Clean Architecture For RazorPage 实现多语言和本地化
    easyui-datagrid 主从表(一对多)表结构,明细在前端存json,一键保存至数据库
    下拉框级联
  • 原文地址:https://www.cnblogs.com/hudean/p/11677269.html
Copyright © 2011-2022 走看看