Web开发之C#:(9)C#常用类库1:String

作者:陆金龙    发表时间:2016-07-21 00:34   


1.String

一个String代表一个不可变的顺序字符集。String是一个密封类。

1.1构造

String s = "abc";

String s = "abc" "123";

string str = new string('h',3);   //字符重复count次,得到字符串

string str1 = new string(new char[] { 'h', 'a' }); //从字符数组得到字符串

1.2比较

Equals

比较两个字符串对象是否相等。比较相等只需要涉及是否忽略大小写。

静态方法:

public static bool Equals(string a, string b);

String.Equals("abc", "Abc", StringComparison.Ordinal); //false

String.Equals("abc", "Abc", StringComparison.OrdinalIgnoreCase);//true

实例方法:

public bool Equals(string value);

Compare

静态方法,比较两个字符串对象的大小。

返回值说明:返回类型为int,比较结果小于零则strA 小于 strB,等于零strA 等于 strB,大于零则strA 大于 strB。

public static int Compare(string strA, string strB);

public static int Compare(string strA, string strB, bool ignoreCase);

public static int Compare(string strA, string strB, StringComparison comparisonType);

使用示例:

String.Compare("abc", "cba", StringComparison.CurrentCulture); 

String.Compare("abc", "CBA", StringComparison.CurrentCultureIgnoreCase);

比较大小,不仅涉及是否忽略大小写,还涉及到字符的排序规则。在不同的语言文化的,两个字符的排序有可能不同,这样比较大小的结果可能恰好相反。因此,需要的话在比较的时候可以指定是否按区域敏感排列规则比较。如果按区域敏感排列规则,则又有按某一固定区域排(InvariantCulture )和按当前区域(CurrentCulture )的区别。

StringComparison的定义如下:

    public enum StringComparison

    {

        CurrentCulture = 0,//使用区域敏感排序规则和当前区域比较字符串。

        CurrentCultureIgnoreCase = 1,//使用区域敏感排序规则、当前区域来比较字符串,同时忽略被比较字符串的大小写。  

InvariantCulture = 2,//使用区域敏感排序规则和固定区域比较字符串。

InvariantCultureIgnoreCase = 3,//使用区域敏感排序规则、固定区域来比较字符串,同时忽略被比较字符串的大小写。

Ordinal = 4,//使用序号排序规则比较字符串。

        OrdinalIgnoreCase = 5,//使用序号排序规则并忽略被比较字符串的大小写,对字符串进行比较。       

}

CompareTo

实例方法,返回结果含义同Compare。

 

将此实例与指定的 System.String 对象进行比较,并指示此实例在排序顺序中是位于指定的 System.String 之前、之后还是与其出现在同一位置。

public int CompareTo(object value);

 

将此实例与指定的 System.Object 进行比较,并指示此实例在排序顺序中是位于指定的 System.Object 之前、之后还是与其出现在同一位置。 

public int CompareTo(string strB);       

StartsWith

实例方法,确定此字符串实例的开始是否与指定的字符串匹配。

public bool StartsWith(string value);

EndsWith

实例方法,确定此字符串实例的结尾是否与指定的字符串匹配。

public bool EndsWith(string value);

Contains

指示指定的 System.String 对象是否出现在此字符串中。

public bool Contains(string value);

 

1.3查找

Substring

从此实例检索子字符串,子字符串从指定的字符位置开始。

 

    // 参数startIndex:此实例中子字符串的起始字符位置(从零开始)。

    // 返回结果:与此实例中在 startIndex 处开头的子字符串等效的一个字符串;如果 startIndex 等于此实例的长度,则为 System.String.Empty。

    public string Substring(int startIndex);

    

    // 参数length:指定子字符串中的字符数。

    // 返回结果:与此实例中在 startIndex 处开头、长度为 length 的子字符串等效的一个字符串,如果 startIndex 等于此实例的长度且 length为零,则为 System.String.Empty。

    public string Substring(int startIndex, int length);

IndexOf

获取指定 Unicode 字符(或字符串)在此实例中的第一个匹配项的索引位置。如果找到该字符(或字符串),则返回要查找字符(或字符串)从零开始的索引位置;如果未找到,则为 -1。

 

// 参数value: 要查找的 Unicode 字符。

public int IndexOf(char value);

 

// 参数startIndex:搜索起始位置。

public int IndexOf(char value, int startIndex);

 

    // 参数value:要搜寻的字符串。

    public int IndexOf(string value);

 

    // 参数startIndex:搜索起始位置。

    public int IndexOf(string value, int startIndex);

LastIndexOf

获取指定 Unicode 字符或字符串在此实例中的最后一个匹配项的索引位置。如果找到该字符,则为 字符或字符串的从零开始的索引位置;如果未找到,则为 -1。

 

    // 参数value: 要查找的 Unicode 字符。

    public int LastIndexOf(char value);

 

    // 参数startIndex:此实例内子字符串的起始位置。

    public int LastIndexOf(char value, int startIndex);

 

    // 参数value:要搜寻的字符串。

    public int LastIndexOf(string value);

 

    // 参数startIndex:搜索起始位置。

    public int LastIndexOf(string value, int startIndex);

1.4替换

Replace

返回一个新字符串,其中此实例中出现的所有指定 Unicode 字符都替换为另一个指定的 Unicode 字符(或所有指定字符串都替换为另一个指定的字符串)。

//oldChar:要被替换的 Unicode 字符。

//newChar:要替换出现的所有 oldChar 的 Unicode 字符。

public string Replace(char oldChar, char newChar);

 

//oldValue:要被替换的字符串。

//newValue:要替换出现的所有 oldValue 的字符串。

public string Replace(string oldValue, string newValue);

 

Trim

Trim方法的作用相当与将空白字符或指定字符替换为空后返回。如:

  Console.WriteLine("abcd".Trim(new char[]{'c','d'}));//输出ab

Console.WriteLine("abcd".TrimStart(new char[] { 'c', 'a', 'b', }));//输出d

 

// 返回从当前字符串的开头和结尾删除所有空白字符后剩余的字符串。

public string Trim();

 

// 返回从当前字符串的开头和结尾删除所出现的所有 trimChars 参数中的字符后剩余的字符串。如果 trimChars 为 null 或空数组,则改为删除空白字符。

public string Trim(params char[] trimChars);

 

// 返回从当前字符串的结尾删除所出现的所有 trimChars 参数中的字符后剩余的字符串。

public string TrimEnd(params char[] trimChars);

 

// 返回从当前字符串的开头删除所出现的所有 trimChars 参数中的字符后剩余的字符串。

public string TrimStart(params char[] trimChars);

 

1.5转换

ToLower

   返回此字符串转换为小写形式的副本。

public string ToLower();

ToUpper

  返回此字符串转换为大写形式的副本。

public string ToUpper();

ToCharArray

将此实例中的字符复制到 Unicode 字符数组,并返回。如果此实例是空字符串,则返回的数组为空且长度为零。

public char[] ToCharArray(); 

1.6 连接和分割

Concat

连接两个指定对象的字符串表示形式,或连接指定的 String 数组或object数组的元素。

// 参数values:字符串实例的数组。

public static string Concat(params string[] values);

        

// 参数args:一个对象数组,其中包含要连接的元素。

public static string Concat(params object[] args);

        

// 返回结果:arg0 和 arg1 的值经过连接的字符串表示形式。

public static string Concat(object arg0, object arg1);

Join

串联字符串数组(或object数组)的所有元素,其中在每个元素之间使用指定的分隔符,并以字符串形式返回。

//separator:要用作分隔符的字符串。

//values:一个数组,其中包含要连接的元素。

public static string Join(string separator, params string[] values);

 

//values:一个数组,其中包含要连接的元素。

public static string Join(string separator, params object[] values);

 

Split

// 返回的字符串数组包含此实例中的子字符串(由指定 Unicode 字符数组的元素分隔)。

// 参数separator:分隔此实例中子字符串的 Unicode 字符数组、不包含分隔符的空数组或 null。

public string[] Split(params char[] separator);

 

// 返回的字符串数组包含此实例中的子字符串(由指定 Unicode 字符数组的元素分隔)。参数指定返回的子字符串的最大数量。

// 参数count:要返回的子字符串的最大数量。

public string[] Split(char[] separator, int count);

// 参数options:指定是否返回空数组元素。要省略返回的数组中的空数组元素,则为 System.StringSplitOptions.RemoveEmptyEntries;要包含返回的数组中的空数组元素,则为

System.StringSplitOptions.None。

public string[] Split(char[] separator, StringSplitOptions options);

1.7 补齐

PadLeft

返回一个新字符串,该字符串通过在此实例中的字符左侧填充空格来达到指定的总长度,从而实现右对齐。

// 参数totalWidth:结果字符串中的字符数,等于原始字符数加上任何其他填充字符。

public string PadLeft(int totalWidth);

 

    返回一个新字符串,该字符串通过在此实例中的字符左侧填充指定的 Unicode 字符来达到指定的总长度,从而使这些字符右对齐。

// 参数totalWidth:结果字符串中的字符数,等于原始字符数加上任何其他填充字符。

// 参数paddingChar:Unicode 填充字符。

public string PadLeft(int totalWidth, char paddingChar);

PadRight

返回一个新字符串,该字符串通过在此字符串中的字符右侧填充空格来达到指定的总长度,从而使这些字符左对齐。

public string PadRight(int totalWidth);

 

返回一个新字符串,该字符串通过在此字符串中的字符右侧填充指定的 Unicode 字符来达到指定的总长度,从而使这些字符左对齐。

public string PadRight(int totalWidth, char paddingChar);

1.8 字符串保留

Intern

如果将同一个字符串赋值给不同的字符串引用,那么系统会多次分配内存空间。

使用字符串保留,当CLR启动的时候,会在内部创建一个哈希表,键是字符串内容,值时字符串在托管堆上的引用。

当一个新的字符串对象需要分配时,CLR首先检测容器中是否包含了该字符串对象,如果已经包含,就直接返回已经存在的字符串对象的引用;如果不存在,则新分配一个字符串对象,并把它添加到内部容器中同时返回该字符串对象的引用。

使用静态方法String.Intern(string)把动态创建的字符串加入到驻留池。

String s1="Hello";

String s2 = new StringBuilder().Append("He").Append("llo").ToString();

String s3 = String.Intern(s2);//取到s1的引用

 

Object.ReferenceEquals(s1,s2);//false

Object.ReferenceEquals(s1,s3);//true

1.9 属性

Length

字符串对象的长度

public int Length { get; }

Empty

表示空字符串。此字段为只读。

public static readonly string Empty;

1.10 索引

获取当前 String 对象中位于指定字符位置的字符, 返回一个 Unicode 字符。

public char this[int index] { get; }

1.11 操作符

==

确定两个指定的字符串是否具有相同的值。

    // 返回结果:如果 a 的值与 b 的值相同,则为 true;否则为 false。

public static bool operator ==(string a, string b);

!=  

  确定两个指定的字符串是否具有不同的值。

// 返回结果:如果 a 的值与 b 的值不同,则为 true;否则为 false。

public static bool operator !=(string a, string b);

1.12 StringBuilder

因为字符串的不可变,直接对字符串操作来实现拼接等效率不高。

通过StringBuilder类来完成字符串的构建,使用StringBuilder的ToString方法返回结果。

public StringBuilder Append(string value); //追加

public StringBuilder AppendLine(string value); //追加行

public StringBuilder AppendFormat(string format, params object[] args)//格式化追加

public StringBuilder Clear(); //清空

1.13文本编码解码

        String s = "Hi Jim";

        Byte[] encodedBytes = Encoding.UTF8.GetBytes(s);

        String decodedStr = Encoding.UTF8.GetString(encodedBytes);

 

        String base64Str = Convert.ToBase64String(encodedBytes);

        encodedBytes = Convert.FromBase64String(base64Str);

        String str = Encoding.UTF8.GetString(encodedBytes);

HttpUtility实现Url编码解码

编码时可以指定编码的,如

System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.Unicode);

System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.UTF8);

System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.GetEncoding( "GB2312 "));

 

解码也可以指定编码的

System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.Unicode);

System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.UTF8);

System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.GetEncoding( "GB2312 "));

HttpContext.Server对象实现Url编码解码

在asp.net后台,可使用HttpContext.Current.Server属性的UrlEncode和UrlDecode方法实现Url的编码和解码。特别是在后台通过Redirect进行页面跳转时,使用HttpContext.Current.Server.UrlEncode进行编码尤其必要。

HttpContext.Current.Server是HttpServerUtility类的一个对象,Server.UrlEncode()、Server.UrlDecode()是对HttpUtility类中相应方法的一个代理调用,因此在编码解码上与System.Web.HttpUtility是等效的。

 

HttpContext.Current.Server.UrlEncode

HttpContext.Current.Server.UrlDecode

Base64编码解码

string factString = "中华人民共和国";

 

//对字符串进行base64编码

byte[] buffer =Encoding.UTF8 .GetBytes(factString);

string Base64Str = Convert.ToBase64String(buffer);

 

    //对字符串进行base64解码

byte[]  buffer = Convert.FromBase64String(Base64Str);

string decodeStr = Encoding.UTF8.GetString(buffer);

 

或者:

//编码

byte[] buffer = Encoding.Default.GetBytes(content);

     content = Convert.ToBase64String(buffer);

//解码

byte[] buffer = Convert.FromBase64String(content);

 content = Encoding.Default.GetString(buffer);

 

Base64 编码后会有“ ”字符,而“ ”是url中的特殊字符,代表空格。Base64 编码过的字符串在url中使用时,应该将“ ”替换为其对应的url编码格式2b%,以免出现错误。

 

Unicode转码

    //(中文)转Unicode码

    public string ToUnicode(string str)

    {

        string UniStr = "";

        for (int i = 0; i < str.Length; i )

        {

            string temp =str[i].ToString();

            if (Regex.IsMatch(temp,"[\\u4E00-\\u9FA5\\uF900-\\uFA2D] "))

            {

                temp = "&#x" ((int)str[i]).ToString("X") ";";

            }

UniStr  = temp;

        }

        return UniStr;

}

 

附:Js Unicode转码

str.replace(/[^\u0000-\u00FF]/g,function ($0) { return escape($0).replace(/(%u)(\w{4})/gi, "&#x$2;")})

 

GB和Unique编码互转

//GB2312转换成unicode编码

        public string GB2Unicode(string str)

        {

            string Hexs = "";

            string HH;

            Encoding GB = Encoding.GetEncoding("GB2312");

            Encoding unicode = Encoding.Unicode;

            byte[] GBBytes = GB.GetBytes(str);

            for (int i = 0; i < GBBytes.Length; i )

            {

                HH = "%" GBBytes[i].ToString("X");

                Hexs = HH;

            }

            return Hexs;

        }

        //unicode编码转换成GB2312汉字

        public string UtoGB(string str)

        {

            string[] ss = str.Split('%');

            byte[] bs = new Byte[ss.Length - 1];

            for (int i = 1; i < ss.Length; i )

            {

                bs[i - 1] = Convert.ToByte(Convert2Hex(ss));   //ss[0]为空串

            }

            char[] chrs = System.Text.Encoding.GetEncoding("GB2312").GetChars(bs);

            string s = "";

            for (int i = 0; i < chrs.Length; i )

            {

                s = chrs.ToString();

            }

            return s;

        }

        private string Convert2Hex(string pstr)

        {

            if (pstr.Length == 2)

            {

                pstr = pstr.ToUpper();

                string hexstr = "0123456789ABCDEF";

                int cint = hexstr.IndexOf(pstr.Substring(0, 1)) * 16 hexstr.IndexOf(pstr.Substring(1, 1));

                return cint.ToString();

            }

            else

            {

                return "";

            }

        }