clr from c# 字符 ,字符串 和 文本处理

1,字符----------在.net中,字符总是16位的Unicode代码值.每个字符都是一个System.Char结构(值类型)的一个实列.

using System;

public class CharStructureSample
{
    public static void Main()
    {
        char chA = 'A';
        char ch1 = '1';
        string str = "test string";

        Console.WriteLine(chA.CompareTo('B'));          //-----------  Output: "-1" (meaning 'A' is 1 less than 'B')
        Console.WriteLine(chA.Equals('A'));             //-----------  Output: "True"
        Console.WriteLine(Char.GetNumericValue(ch1));   //-----------  Output: "1"
        Console.WriteLine(Char.IsControl('\t'));        //-----------  Output: "True"
        Console.WriteLine(Char.IsDigit(ch1));           //-----------  Output: "True"
        Console.WriteLine(Char.IsLetter(','));          //-----------  Output: "False"
        Console.WriteLine(Char.IsLower('u'));           //-----------  Output: "True"
        Console.WriteLine(Char.IsNumber(ch1));          //-----------  Output: "True"
        Console.WriteLine(Char.IsPunctuation('.'));     //-----------  Output: "True"
        Console.WriteLine(Char.IsSeparator(str, 4));    //-----------  Output: "True"
        Console.WriteLine(Char.IsSymbol('+'));          //-----------  Output: "True"
        Console.WriteLine(Char.IsWhiteSpace(str, 4));   //-----------  Output: "True"
        Console.WriteLine(Char.Parse("S"));             //-----------  Output: "S"
        Console.WriteLine(Char.ToLower('M'));           //-----------  Output: "m"
        Console.WriteLine('x'.ToString());              //-----------  Output: "x"
    }
}

可以使用GetUnicodeCategory来处理字符的类别

using System;
using System.Globalization;

class Example
{
   public static void Main()
   {
      // Define a string with a variety of character categories.
      String s = "The red car drove down the long, narrow, secluded road.";
      // Determine the category of each character.
      foreach (var ch in s)
         Console.WriteLine("'{0}': {1}", ch, Char.GetUnicodeCategory(ch));
   }
}
// The example displays the following output:
//      'T': UppercaseLetter
//      'h': LowercaseLetter
//      'e': LowercaseLetter
//      ' ': SpaceSeparator
//      'r': LowercaseLetter
//      'e': LowercaseLetter
//      'd': LowercaseLetter
//      ' ': SpaceSeparator
//      'c': LowercaseLetter
//      'a': LowercaseLetter
//      'r': LowercaseLetter
//      ' ': SpaceSeparator
//      'd': LowercaseLetter
//      'r': LowercaseLetter
//      'o': LowercaseLetter
//      'v': LowercaseLetter
//      'e': LowercaseLetter
//      ' ': SpaceSeparator
//      'd': LowercaseLetter
//      'o': LowercaseLetter
//      'w': LowercaseLetter
//      'n': LowercaseLetter
//      ' ': SpaceSeparator
//      't': LowercaseLetter
//      'h': LowercaseLetter
//      'e': LowercaseLetter
//      ' ': SpaceSeparator
//      'l': LowercaseLetter
//      'o': LowercaseLetter
//      'n': LowercaseLetter
//      'g': LowercaseLetter
//      ',': OtherPunctuation
//      ' ': SpaceSeparator
//      'n': LowercaseLetter
//      'a': LowercaseLetter
//      'r': LowercaseLetter
//      'r': LowercaseLetter
//      'o': LowercaseLetter
//      'w': LowercaseLetter
//      ',': OtherPunctuation
//      ' ': SpaceSeparator
//      's': LowercaseLetter
//      'e': LowercaseLetter
//      'c': LowercaseLetter
//      'l': LowercaseLetter
//      'u': LowercaseLetter
//      'd': LowercaseLetter
//      'e': LowercaseLetter
//      'd': LowercaseLetter
//      ' ': SpaceSeparator
//      'r': LowercaseLetter
//      'o': LowercaseLetter
//      'a': LowercaseLetter
//      'd': LowercaseLetter
//      '.': OtherPunctuation
  • 单个字符可能由多个Char对象构成

2,String类

3,Enum类

4,数组

 int[][] i = new int[3][];//交错数组,表示i 是一个指向 int [] 类型实列的数组
            i[0] = new int[10];
            i[1] = new int[11];
            i[2] = new int[12];
            int[,] j = new int[3, 5];//多维素组

4.1 数组转型

  • 必须维数一致,下基一致
  • 并且存在从元素源类型到目标源类型的隐式转换.
     object[] obj1= new object[] { new object(), new object() };
                string[] str1 = { "abc", "efg" };
                obj1 = str1;
                obj1 = new object[str1.Length];
                Array.Copy(str1, obj1, str1.Length);

使用,System.Buffer.BlockCopy

 public class ArrayRef
    {
        public static void DisplayArray(Array arr, string name)
        {
            Console.WindowWidth = 120;
            Console.Write("{0,11}:", name);
            for (int ctr = 0; ctr < arr.Length; ctr++)
            {
                byte[] bytes;
                if (arr is long[])
                    bytes = BitConverter.GetBytes((long)arr.GetValue(ctr));
                else
                    bytes = BitConverter.GetBytes((short)arr.GetValue(ctr));

                foreach (byte byteValue in bytes)
                    Console.Write(" {0:X2}", byteValue);
            }
            Console.WriteLine();
        }

        // Display the individual array element values in hexadecimal.
        public static void DisplayArrayValues(Array arr, string name)
        {
            // Get the length of one element in the array.
            int elementLength = Buffer.ByteLength(arr) / arr.Length;
            string formatString = String.Format(" {{0:X{0}}}", 2 * elementLength);
            Console.Write("{0,11}:", name);
            for (int ctr = 0; ctr < arr.Length; ctr++)
                Console.Write(formatString, arr.GetValue(ctr));

            Console.WriteLine();
        }
        public static void test()
        {
            // These are the source and destination arrays for BlockCopy.
            short[] src = { 258, 259, 260, 261, 262, 263, 264,
                          265, 266, 267, 268, 269, 270 };
            long[] dest = { 17, 18, 19, 20 };

            // Display the initial value of the arrays in memory.
            Console.WriteLine("Initial values of arrays:");
            Console.WriteLine("   Array values as Bytes:");
            DisplayArray(src, "src");
            DisplayArray(dest, "dest");
            Console.WriteLine("   Array values:");
            DisplayArrayValues(src, "src");
            DisplayArrayValues(dest, "dest");
            Console.WriteLine();

            // Copy bytes 5-10 from source to index 7 in destination and display the result.
            Buffer.BlockCopy(src, 5, dest, 7, 6);
            Console.WriteLine("Buffer.BlockCopy(src, 5, dest, 7, 6 )");
            Console.WriteLine("   Array values as Bytes:");
            DisplayArray(src, "src");
            DisplayArray(dest, "dest");
            Console.WriteLine("   Array values:");
            DisplayArrayValues(src, "src");
            DisplayArrayValues(dest, "dest");
            Console.WriteLine();

            // Copy bytes 16-20 from source to index 22 in destination and display the result. 
            Buffer.BlockCopy(src, 16, dest, 22, 5);
            Console.WriteLine("Buffer.BlockCopy(src, 16, dest, 22, 5)");
            Console.WriteLine("   Array values as Bytes:");
            DisplayArray(src, "src");
            DisplayArray(dest, "dest");
            Console.WriteLine("   Array values:");
            DisplayArrayValues(src, "src");
            DisplayArrayValues(dest, "dest");
            Console.WriteLine();

            // Copy overlapping range of bytes 4-10 to index 5 in source.
            Buffer.BlockCopy(src, 4, src, 5, 7);
            Console.WriteLine("Buffer.BlockCopy( src, 4, src, 5, 7)");
            Console.WriteLine("   Array values as Bytes:");
            DisplayArray(src, "src");
            DisplayArray(dest, "dest");
            Console.WriteLine("   Array values:");
            DisplayArrayValues(src, "src");
            DisplayArrayValues(dest, "dest");
            Console.WriteLine();

            // Copy overlapping range of bytes 16-22 to index 15 in source. 
            Buffer.BlockCopy(src, 16, src, 15, 7);
            Console.WriteLine("Buffer.BlockCopy( src, 16, src, 15, 7)");
            Console.WriteLine("   Array values as Bytes:");
            DisplayArray(src, "src");
            DisplayArray(dest, "dest");
            Console.WriteLine("   Array values:");
            DisplayArrayValues(src, "src");
            DisplayArrayValues(dest, "dest");
        }
    }
Initial values of arrays:
   Array values as Bytes:
        src: 02 01 03 01 04 01 05 01 06 01 07 01 08 01 09 01 0A 01 0B 01 0C 01 0D 01 0E 01
       dest: 11 00 00 00 00 00 00 00 12 00 00 00 00 00 00 00 13 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00
   Array values:
        src: 0102 0103 0104 0105 0106 0107 0108 0109 010A 010B 010C 010D 010E
       dest: 0000000000000011 0000000000000012 0000000000000013 0000000000000014

Buffer.BlockCopy(src, 5, dest, 7, 6 )
   Array values as Bytes:
        src: 02 01 03 01 04 01 05 01 06 01 07 01 08 01 09 01 0A 01 0B 01 0C 01 0D 01 0E 01
       dest: 11 00 00 00 00 00 00 01 05 01 06 01 07 00 00 00 13 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00
   Array values:
        src: 0102 0103 0104 0105 0106 0107 0108 0109 010A 010B 010C 010D 010E
       dest: 0100000000000011 0000000701060105 0000000000000013 0000000000000014

Buffer.BlockCopy(src, 16, dest, 22, 5)
   Array values as Bytes:
        src: 02 01 03 01 04 01 05 01 06 01 07 01 08 01 09 01 0A 01 0B 01 0C 01 0D 01 0E 01
       dest: 11 00 00 00 00 00 00 01 05 01 06 01 07 00 00 00 13 00 00 00 00 00 0A 01 0B 01 0C 00 00 00 00 00
   Array values:
        src: 0102 0103 0104 0105 0106 0107 0108 0109 010A 010B 010C 010D 010E
       dest: 0100000000000011 0000000701060105 010A000000000013 00000000000C010B

Buffer.BlockCopy( src, 4, src, 5, 7)
   Array values as Bytes:
        src: 02 01 03 01 04 04 01 05 01 06 01 07 08 01 09 01 0A 01 0B 01 0C 01 0D 01 0E 01
       dest: 11 00 00 00 00 00 00 01 05 01 06 01 07 00 00 00 13 00 00 00 00 00 0A 01 0B 01 0C 00 00 00 00 00
   Array values:
        src: 0102 0103 0404 0501 0601 0701 0108 0109 010A 010B 010C 010D 010E
       dest: 0100000000000011 0000000701060105 010A000000000013 00000000000C010B

Buffer.BlockCopy( src, 16, src, 15, 7)
   Array values as Bytes:
        src: 02 01 03 01 04 04 01 05 01 06 01 07 08 01 09 0A 01 0B 01 0C 01 0D 0D 01 0E 01
       dest: 11 00 00 00 00 00 00 01 05 01 06 01 07 00 00 00 13 00 00 00 00 00 0A 01 0B 01 0C 00 00 00 00 00
   Array values:
        src: 0102 0103 0404 0501 0601 0701 0108 0A09 0B01 0C01 0D01 010D 010E
       dest: 0100000000000011 0000000701060105 010A000000000013 00000000000C010B    }
  • BitConvert----用于将基数据类型转换为Byte数组,或者将Byte数组转换为基数据类型.
  • Array的许多静态方法:
  • public static int BinarySearch (Array array, object value);
  • 如果搜索到该值,则返回其索引,否则返回一个负数,~result只是第一个比该value大的数组元素的位置.
    public static void CallArrayBinSearch()
            {
                int[] r1 = { 1, 2, 3, 7, 8, 9 };
                int result = Array.BinarySearch(r1, 6);
                int result1 = Array.BinarySearch(r1, 7);
                Console.WriteLine(~result + " " + result1);
            }
    //结果 -4(3),3 表明,比6大的第一个元素是3


聊一聊排序:  1,元素的顺序根本比较是 x.CompareTo( y)

    • x<y ,return –1 定义的是升序排列----意思是从左到右边,从上到下来看. 对于升序排列的元素则,所有的x.CompareTo(y),返回-1
    • x=y,return 0,定义相等,x.CompareTo(y)返回 0
    • x>y,return 1,表明是降序----意思是从x.
      • using System;
        using System.Collections.Generic;
        
        public class ReverseComparer: IComparer<string>
        {
            public int Compare(string x, string y)
            {
                // Compare y and x in reverse order.
                return y.CompareTo(x);
            }
        }
        
        public class Example
        {
            public static void Main()
            {
                string[] dinosaurs = {"Pachycephalosaurus",
                                      "Amargasaurus",
                                      "Tyrannosaurus",
                                      "Mamenchisaurus",
                                      "Deinonychus",
                                      "Edmontosaurus"};
        
                Console.WriteLine();
                foreach( string dinosaur in dinosaurs )
                {
                    Console.WriteLine(dinosaur);
                }
        
                ReverseComparer rc = new ReverseComparer();
        
                Console.WriteLine("\nSort");
                Array.Sort(dinosaurs, rc);
        
                Console.WriteLine();
                foreach( string dinosaur in dinosaurs )
                {
                    Console.WriteLine(dinosaur);
                }
        
                Console.WriteLine("\nBinarySearch for 'Coelophysis':");
                int index = Array.BinarySearch(dinosaurs, "Coelophysis", rc);
                ShowWhere(dinosaurs, index);
        
                Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
                index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc);
                ShowWhere(dinosaurs, index);
            }
        
            private static void ShowWhere<T>(T[] array, int index)
            {
                if (index<0)
                {
                    // If the index is negative, it represents the bitwise
                    // complement of the next larger element in the array.
                    //
                    index = ~index;
        
                    Console.Write("Not found. Sorts between: ");
        
                    if (index == 0)
                        Console.Write("beginning of array and ");
                    else
                        Console.Write("{0} and ", array[index-1]);
        
                    if (index == array.Length)
                        Console.WriteLine("end of array.");
                    else
                        Console.WriteLine("{0}.", array[index]);
                }
                else
                {
                    Console.WriteLine("Found at index {0}.", index);
                }
            }
        }
        
        /* This code example produces the following output:
        
        Pachycephalosaurus
        Amargasaurus
        Tyrannosaurus
        Mamenchisaurus
        Deinonychus
        Edmontosaurus
        
        Sort
        
        Tyrannosaurus
        Pachycephalosaurus
        Mamenchisaurus
        Edmontosaurus
        Deinonychus
        Amargasaurus
        
        BinarySearch for 'Coelophysis':
        Not found. Sorts between: Deinonychus and Amargasaurus.
        
        BinarySearch for 'Tyrannosaurus':
        Found at index 0.
         */
    • CompareTo(y)返回1.


对于

BinarySearch(Array, Object, IComparer)//元素实现 int Compare(T x, T y)接口
public static int BinarySearch (Array array, int index, int length, object value, System.Collections.IComparer comparer);指定了搜索范围

  • Array.Clear(Array, Int32, Int32) 方法
    public static void Clear (Array array, int index, int length);


  • Array.ConstraineCopy----完全拷贝Array的内容,深拷贝.拷贝后,两个区域无关.
  • public static void ConstrainedCopy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);


  •      Array.ConvertAll---数组进行转换,这也是进行深度拷贝的方法.可以生成新对象.
    public static TOutput[] ConvertAll<TInput,TOutput> (TInput[] array, Converter<TInput,TOutput> converter);
    //使用Converter委托进行数据类型转换
    
    public delegate TOutput Converter<in TInput,out TOutput>(TInput input);


    public class SamplesArray2{
    
       public static void Main()  {
          // Creates and initializes the source Array.
          Array myArrayZero=Array.CreateInstance( typeof(String), 3 );
          myArrayZero.SetValue( "zero", 0 );
          myArrayZero.SetValue( "one", 1 );
    
          // Displays the source Array.
          Console.WriteLine( "The array with lower bound=0 contains:" );
          PrintIndexAndValues( myArrayZero );
    
          // Creates and initializes the target Array.//创建非零数组
          int[] myArrLen = { 4 };
          int[] myArrLow = { 2 };
          Array myArrayTwo=Array.CreateInstance( typeof(String), myArrLen, myArrLow );
          myArrayTwo.SetValue( "two", 2 );
          myArrayTwo.SetValue( "three", 3 );
          myArrayTwo.SetValue( "four", 4 );
          myArrayTwo.SetValue( "five", 5 );
    
          // Displays the target Array.
          Console.WriteLine( "The array with lower bound=2 contains:" );
          PrintIndexAndValues( myArrayTwo );
    
          // Copies from the array with lower bound=0 to the array with lower bound=2.
          myArrayZero.CopyTo( myArrayTwo, 3 );
    
          // Displays the modified target Array.
          Console.WriteLine( "\nAfter copying to the target array from index 3:" );
          PrintIndexAndValues( myArrayTwo );
       }
    
       public static void PrintIndexAndValues( Array myArray )  {
          for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
             Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
       }
    }
    /*
    This code produces the following output.
    
    The array with lower bound=0 contains:
        [0]:    zero
        [1]:    one
        [2]:
    The array with lower bound=2 contains:
        [2]:    two
        [3]:    three
        [4]:    four
        [5]:    five
    
    After copying to the target array from index 3:
        [2]:    two
        [3]:    zero
        [4]:    one
        [5]:
    */



  • Array.CreateInstance---
    重载
    
    CreateInstance(Type, Int32)
    创建使用从零开始的索引、具有指定 Array 和长度的一维 Type。
    CreateInstance(Type, Int32[])
    创建索引从零开始、具有指定 Array 和维长的多维 Type。 维的长度在一个 32 位整数数组中指定。
    CreateInstance(Type, Int64[])
    创建索引从零开始、具有指定 Array 和维长的多维 Type。 维的长度在一个 64 位整数数组中指定。
    CreateInstance(Type, Int32, Int32)
    创建使用从零开始的索引、具有指定 Array 和维长的二维 Type。
    CreateInstance(Type, Int32[], Int32[])
    创建具有指定下限、指定 Array 和维长的多维 Type。
    CreateInstance(Type, Int32, Int32, Int32)
    创建使用从零开始的索引、具有指定 Array 和维长的三维 Type。*/
  • Array.Exsits---
  • public static bool Exists<T> (T[] array, Predicate<T> match);
    //----------指定委托,判断元素是否匹配
    public delegate bool Predicate<in T>(T obj);
    //-----------委托
    public static T Find<T> (T[] array, Predicate<T> match);
    //----返回找到的元素T,如果没找到则是default(T)
    public static T[] FindAll<T> (T[] array, Predicate<T> match);
    //返回所有找到的元素T.
    public static int FindIndex<T> (T[] array, Predicate<T> match);
    //返回匹配元素的index
    public static T FindLast<T> (T[] array, Predicate<T> match);
    //返回最后匹配的元素T
    public static int FindLastIndex<T> (T[] array, Predicate<T> match);
    //返回最后匹配的元素T的索引
    public static void ForEach<T> (T[] array, Action<T> action);
    //对所有元素执行方法ACTION
    public int GetLength (int dimension);
    //获取数组某维的长度
    public long GetLongLength (int dimension);
    //获取数组某维64位长度
    
posted @ 2020-02-06 20:49  frogkiller  阅读(207)  评论(0编辑  收藏  举报