zoukankan      html  css  js  c++  java
  • C# 字符串处理

    C# 字符串处理

            .NET 提供了String类和System.Text命名空间来高速实现字符串处理功能。

    字符串比較

            比較字符串是指依照字典排序的规则,推断两个字符串的大小。前面的字母要小于后面的字母。String类中,常见的比較字符串的方法有Compare、CompareTo、CompareOrdinal以及Equals等。

    Compare方法

            Compare方法是String类的静态方法,用于全面比較两个字符串对象。包括多种重载方式:
    Int Compare(string strA, string strB)
    Int Compare(string strA, string strB, bool ignoreCase)
    Int Compare(string strA, string strB, bool ignoreCase, CultureInfo)
    Int Compare(string strA, int indexA, string strB, int indexB, int length)
    Int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
            各參数的含义例如以下:
    • strA,strB--待比較的两个字符串;
    • ignoreCase--指定是否考虑大写和小写,当取true时忽略大写和小写;
    • indexA,indexB--须要比較两个字符串的子串时,indexA和indexB分别为子字符串的起始位置;
    • length--待比較字符串的最大长度;
    • culture--字符串的区域性信息。
            Compare方法的返回值:若strA>strB返回正整数; 若strA=strB,返回0; 若strA<strB,返回负整数。
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "你好";
                string strB = "你好吗";
                // 字符串比較
                Console.WriteLine(string.Compare(strA, strB));
                Console.WriteLine(string.Compare(strA, strA));
                Console.WriteLine(string.Compare(strB, strA));
            }
        }
    }
    
            输出:

            说明:CompareOrdinal方法和Compare方法很类似,但不考虑区域性问题,以下不再具体介绍CompareOrdinal方法。

    CompareTo方法

            CompareTo方法将当前字符串对象与还有一个字符串对象作比較,作用与Compare方法类似,返回值也是同样的。
            CompareTo方法和Compare方法差别在于:
    1. CompareTo方法不是静态方法,能够通过一个String对象调用;
    2. CompareTo方法没有重载形式,仅仅能依照大写和小写敏感的方式比較两个整串。
            以下使用CompareTo比較两个字符串:

    string strA = "你好";
    string strB = "你好吗";
    Console.WriteLine(strA.CompareTo(strB));

    Equals方法

            假设两个字符串相等,Equals()返回值为true;否则,返回false。
    string strA = "你好";
    string strB = "你好吗";
    Console.WriteLine(string.Equals(strA, strB));
    Console.WriteLine(strA.Equals(strB));

    定位字符及子串

            定位子串是指一个字符串中寻找当中包括的子串或者某个字符,String类中常见方法包括StartsWith/EndsWith、IndexOf/LastIndexOf 以及 IndexOfAny/LastIndexOfAny。

    StartsWith/EndsWith

            StartWith方法能够推断一个字符串对象是否以还有一个子字符串开头,假设是,返回true。
    Public bool StartsWith(String value);
            当中,value表示待判定的子字符串。
            EndsWith方法推断一个字符串对象是否以还有一个子字符串结尾。

    IndexOf/LastIndexOf

            IndexOf方法用于搜索在上一个字符串中,某个特定的字符或字符串第一次出现的位置,该方法区分大写和小写,并从字符串的首字符開始以0计数。假设字符串中不包括这个字符或子串,则返回-1。IndexOf主要有下面重载形式:
            定位字符
    Int IndexOf(char value)
    Int IndexOf(char value, int startIndex)
    Int IndexOf(char value, int startIndex, int count)
            定位子串
    int IndexOf(string value)
    int IndexOf(string value, int startIndex)
    int IndexOf(string value, int startIndex, int count)
            各參数的含义是:
    • value--带定位的字符或子串;
    • startIndex--在总串中開始搜索的起始位置;
    • count--在总串中从起始位置開始搜索的字符数。
    string strA = "Hello";
    Console.WriteLine(strA.IndexOf('l'));
            同IndexOf类似,LastIndexOf方法用于搜索在一个字符串中,某个特定的字符或子串最后一次出现的位置。

    IndexOfAny/LastIndexOfAny

            IndexOfAny方法功能与IndexOf类似,差别在于它能够在一个字符串中搜索一个字符数组中随意字符第一次出现的位置。相同,该方法区分大写和小写,并从字符串的首字符開始以0计数。假设字符串中不包括这个字符或子串,则返回-1。
            IndexOfAny有下面重载形式:
    int IndexOfAny(char[] anyOf)
    int IndexOfAny(char[] anyOf, int startIndex)
    int IndexOfAny(char[] anyOf, int startIndex, int count)
            各參数的含义:
    • anyOf--待定位的字符数组,方法将返回这个数组中随意一个字符第一次出现的位置;
    • startIndex--在总串中開始搜索的起始位置;
    • count--在总串中从起始位置開始搜索的字符数。
    string strA = "Hello";
    char[] anyOf = { 'e', 'o' };
    Console.WriteLine(Convert.ToString(strA.IndexOfAny(anyOf)));
    Console.WriteLine(Convert.ToString(strA.LastIndexOfAny(anyOf)));
            同IndexOfAny类似,LastIndexOfAny用于在一个字符串中搜索一个字符数组中随意字符最后一次出现的位置。

    格式字符串

            Format方法用于创建格式化的字符串以及连接多个字符串对象。最经常使用的重载形式为
    public static string Format(string Format, params object[] arge);
    
    •         format--用于指定返回的字符串的格式;
    •         args--一系列变量參数。
    string newStr = string.Format("{0},{1}!!!", strA, strB);
            在特定的应用中,Format方法也非常方便。比如,将当前时间格式为"YYYY-MM-DD"形式:
    DateTime DTA = DateTime.Now();
    string strB = string.Format("{0:d}", DTA);
    
            说明:{0:d}表示将时间格式化为短日期表示形式。

    截取字符串

            截取字符串须要用到String类的Substring方法,该方法用来从字符传中检索子字符串,有下面重载形式:

    从字符串中检索子字符串,子字符串从指定的字符位置開始

    public string Substring(int startIndex)
            startIndex--字符串中子字符串的起始字符位置。
            返回值:一个String对象,等于字符串中从startIndex開始的子字符串,假设startIndex等于此字符串的长度,返回Empty。

    从字符串中检索子字符串,子字符串从指定的字符位置開始且具有指定的长度

    public string Substring(int startIndex, int length)
    
            startIndex--字符串中子字符串的起始字符位置。
            length--子字符串中的字符数。
            返回值:一个String对象,等于字符串中从startIndex開始的长度为length的子字符串,假设startIndex等于此字符串的长度,且length为0,返回Empty。

    分隔字符串

            使用Split方法能够将一个字符串,依照某个分隔符,切割成一系列小的字符串。
            Split方法有多个重载形式,最常见的:
    public string[] split(params char[] separator);
    
            separator--一个数组,包括分隔符。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello^^world";
                char[] separator={'^'};
                string[] splitstrings=new string[100];
                splitstrings=strA.Split(separator);
                int i= 0;
                while(i<splitstrings.Length)
                {
                    Console.WriteLine("item{0}:{1}",i,splitstrings[i]);
                    i++;
                }
                Console.ReadLine();
            }
        }
    }
            输出:

    插入和填充字符串

            String类能够用Insert方法在字符串的任何位置插入随意字符。而使用PadLeft/PadRight方法,能够在一个字符串的左右两側能够进行字符填充。

    Insert方法

            Insert方法用于在一个字符串的指定位置插入还有一个字符串,从而构造一个新的字符串。最经常使用的重载形式:
    public string Insert(int startIndex, string value);
            startIndex--用于指定要插入的位置,索引从0開始。
            value--指定要插入的字符串。
            返回值--指定字符串的一个新String等效项,但在位置startIndex处插入value。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello^^world";
                string strB = "Good morning!";
                string newStr = strA.Insert(1, strB);
                Console.WriteLine(newStr);
                Console.ReadLine();
            }
        }
    }
            输出:

    PadLeft/PadRight

            PadLeft用于在一个字符串左側进行字符填充,使其达到一定的长度。有下面重载形式:
    public string PadLeft(int totalWidth)
    public string PadLeft(int totalWidth, char paddingChar)
    
            totalWidth--指定填充后的字符长度。
            paddingChar--指定要填充的字符,假设缺省,则填充空格符号。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello^^world";
                string newStr; 
                newStr = strA.PadLeft(16, '*');
                Console.WriteLine(newStr);
                Console.ReadLine();
            }
        }
    }
            输出:

            PadRight功能类似,不再赘述。

    删除和剪切字符串

            String类使用Remove在字符串任何位置删除随意长度子字符串,也能够使用Trim、TrimEnd和TrimStart剪切掉字符串中的一些特定字符串。

    Remove方法

            Remove方法从一个字符串的指定位置開始,删除指定数量的字符。最经常使用的语法格式:
    Public String Remove(int startIndex, int count);
    
            startIndex--用于指定開始删除的位置,索引从0開始。
            count--指定删除的字符数量。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello^^world";
                string newStr; 
                newStr = strA.PadLeft(16, '*');
                Console.WriteLine(newStr);
                Console.WriteLine(newStr.Remove(2, 3));
                Console.ReadLine();
            }
        }
    }
            输出:

    Trim方法

            有下面重载形式:

    从字符串的開始位置和末尾移除空白字符的全部匹配项。

    public string Trim()
            返回值--一个新String,相当于将指定字符串首位空白字符移除后形成的字符串。

    从字符串的開始位置和末尾移除数组中指定的一组字符的全部匹配项

    public string Trim(params char[] trimChars)
            trimChars--数组包括了指定要去掉的字符,假设缺省,则删除空格符号)。
            返回值--从指定字符串的開始和结尾移除trimChars中字符的全部匹配项后剩余的String。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello^^world";
                string newStr; 
                newStr = strA.PadLeft(16, '*');
                Console.WriteLine(newStr);
                char[] strB={'*','d'};
                Console.WriteLine(newStr.Trim(strB));
                Console.ReadLine();
            }
        }
    }
           输出:

    TrimStart方法

            TrimStart方法用来从字符串的開始位置移除数组中指定的一组字符的全部匹配项。
    public string TrimStart(params char[] trimChars)
    
            trimChars--数组包括了指定要去掉的字符,假设缺省,则删除空格符号)。
            返回值--从指定字符串的開始位置移除trimChars中字符的全部匹配项后剩余的String。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello^^world";
                char[] strB = { 'H', 'o' };
                string strC = strA.TrimStart(strB);
                Console.WriteLine(strC);
                Console.Read();
            }
        }
    }
            输出:

            PS:注意字符区分大写和小写。如上面改为"h",则仍然输出Hello^^World。

    TrimEnd方法

            类比TrimStart就可以。

    复制字符串

            String类包括了复制字符串的两种方法Copy和CopyTo。

    Copy方法

            若要把一个字符串赋值到还有一个字符数组中,能够使用String的静态方法Copy来实现。
    public static string Copy(string str);
            str--为须要复制的源字符串,方法返回目标字符串。
            返回值--与str具有同样值的新String。

    CopyTo方法

            CopyTo方法功能更为丰富,能够复制源字符串的一部分到一个字符数组中。另外,它不是静态方法。
    public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
            各參数的含义:
    • sourceIndex--须要复制的字符的起始位置。
    • destination--目标字符数组。
    • destinationIndex--指定目标数组的開始存放位置。
    • count--指定要复制的字符个数。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello^^world";
                char[] strB = new char[100];
                strA.CopyTo(3, strB, 0, 3);
                Console.WriteLine(strB);
                Console.Read();
            }
        }
    }
            输出:

    替换字符串

            假设要替换掉某个字符串的某些特定字符或者某个子串,能够使用Repalce方法。

    Replace方法

            其语法形式主要有:
    public string Replace(char oldChar,char newChar)
    public string Replace(string oldValue,string newValue)
    
    •         oldChar--待替换的字符。
    •         oldChar--待替换的子串。
    •         newChar--替换后的新字符。
    •         newValue--替换后的新子串。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string strA = "Hello";
                string strB=strA.Replace("ll","r");
                Console.WriteLine(strB);
                Console.Read();
            }
        }
    }
            输出:

    StringBuilder的定义和使用

            StringBuilder类位于System.Text命名空间下,它表示可变字符串。

    StringBuilder的定义

    StringBuilder myStringBuilder=new StringBuilder();
            StringBuilder的构造函数:
    • StringBuilder()--初始化StringBuilder类的新实例。
    • StringBuilder(Int32)--使用指定的容量初始化StringBuilder类的新实例。
    • StringBuilder(String)--使用指定的字符串初始化StringBuilder类的新实例。
    • StringBuilder(Int32,Int32)--初始化StringBuilder类的新实例,该类起始于指定容量而且可增长到指定的最大容量。
    • StringBuilder(String,Int32)--使用指定的字符串和容量初始化StringBuilder类的新实例。
    • StringBuilder(String,Int32,Int32,Int32)--使用指定的子字符串和容量初始化StringBuilder类的新实例。

    StringBuilder使用

            StringBuilder类经常使用属性说明:
    • Capacity--获取或设置可包括在当前实例所分配的内存中的最大字符数。
    • Chars--获取或设置此实例中指定字符位置处的字符。
    • Length--获取或设置此实例的长度。
    • MaxCapacity--获取此实例的最大容量。
            StringBuilder类经常使用的方法说明:
    • Append--在此实例的结尾追加指定对象的字符串表示形式。
    • AppendFormat--向此实例追加包括零个或很多其它格式规范的格式化字符串。每一个格式规范由对应对象的字符串表示形式替换。
    • AppendLine--将默认的行终止符(或指定字符串的副本和默认的行终止符)追加到此实例的结尾。
    • CopyTo--将此实例的指定段中的字符拷贝到目标Char数组的指定段中。
    • EnsureCapacity--将确保StringBuilder的此实例的容量至少是指定值。
    • Insert--将指定对象的字符串表示形式插入到此实例中的指定字符位置。
    • Remove--将指定范围的字符从此实例中移除。
    • Replace--将此实例中全部的指定字符或字符串替换为其它的指定字符或字符串。
    • ToString--将StringBuilder的值转化为String。
            StringBuilder类表示值为可变字符序列的对象,其值可变的原因是同过追加、删除、替换或插入字符而创建后的实例能够对其进行改动。差点儿全部改动此类的实例方法都返回对同一实例的引用。
            StringBuilder的容量是实例在不论什么给定时间可存储的最大字符数,而且大于或等于实例值的字符串表示形式的长度。容量能够通过Capacity属性或EnsureCapacity方法来添加或降低,但不能小于Length属性的值。
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                StringBuilder Builder = new StringBuilder("Hello", 100);
                Builder.Append(" World");
                Console.WriteLine(Builder);
                Builder.AppendFormat("{0} End", "@");
                Console.WriteLine(Builder);
                Builder.AppendLine("This is one line.");
                Console.WriteLine(Builder);
                Builder.Insert(0, "Begin");
                Console.WriteLine(Builder);
                Builder.Remove(19, Builder.Length - 19);
                Console.WriteLine(Builder);
                Builder.Replace("Begin", "Begin:");
                Console.WriteLine(Builder);
                Console.ReadLine();
            }
        }
    }
            输出:

    可变字符串类StringBuilder和String的差别

            每次使用String类的方法时,都要在内存中创建一个新的字符串对象,须要为该对象分配新的空间。在须要对字符串运行反复改动的情况下系统开销可能很昂贵。假设要改动字符串而不创建新的对象,请使用StringBuilder类,避免产生过多暂时对象。
  • 相关阅读:
    Dart中的类型转换总结:
    【Dart学习】--Dart之数组(List)的相关方法总结
    Navigator的使用:
    001——Angular环境搭建、运行项目、搭建项目
    Dart中的数据类型转换:
    Flutter中的Stack、Align、Positioned的使用
    Flutter设置图片为正方形
    顶部导航TabBar、TabBarView、DefaultTabController
    《慕客网:IOS基础入门之Foundation框架初体验》学习笔记 <二> NSMutableString
    Swift随记
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4050296.html
Copyright © 2011-2022 走看看