C# 数据类型
Char Array
Char Array储存string data。有两个方法建立StringBuilder和Character array
【Character array】
用来存储character data,比如字母和数字
好处:array element被储存在内存中的一块,避免了存储于分开的对象所带来的内存消耗。Char是基本的变量类型,她不是存储reference而是存储在内存本身。
建立char array:
using System; class Program { static void Main() { char[] array1 = { 's', 'a', 'm' }; char[] array2 = new char[] { 's', 'a', 'm' }; char[] array3 = new char[3]; //可以使用这个方法,后面用for循环添加每一个character array3[0] = 's'; array3[1] = 'a'; array3[2] = 'm'; // Write total length: Console.WriteLine(array1.Length + array2.Length + array3.Length); } }
Output
9
【StringBuilder】
Example using char array: faster [C#]
class Program { static void Main() { // Use a new char array. char[] buffer = new char[100]; for (int i = 0; i < 100; i++) { buffer[i] = 'a'; } string result = new string(buffer); } }
The array is instantiated with the new char syntax, and this allocates 100 2-byte chars.
We assign each index to the char we want to append. This example uses the new string constructor.
Example using StringBuilder: slower [C#]
using System.Text; class Program { static void Main() { // Declare new StringBuilder and append to it 100 times. StringBuilder builder = new StringBuilder(100); for (int i = 0; i < 100; i++) { builder.Append('a'); } string result = builder.ToString(); } }
The biggest advantage the StringBuilder method has is that you could keep appending items to the buffer after the 100th char.
总结:
1:Char Array比StringBuilder要来的快,因为其没有预制的很多方法。
2:StringBuilder可以Append更多的chars。StringBuilder可以使用很多预制的方法,在多数情况下使用起来很方便,但是对于简单的case,还是CharArray来的快。
3:当事先知道有多少character需要储存,我们使用Char Array。
String
【string.split】
分谁:
- 分一个特定string中的 ' ', \r ,\n ,',' ,按非字母元素分 等等
- 分***.txt
- Seprate words
- 分文件路径: @"C:\Users\Sam\Documents\Perls\Main"
分法:(2个以上的char和string分要先做一个new,实际上是按sting[]分)
- char分: ‘a’, ‘ ’, ‘\r’
- char[]分: char[] delimiters = new char[] { '\r', '\n' };
- string[]分:
const string dir = @"C:\Users\hb92540\AAppData\LocalAA\Temporary Projects\ConsoleAApplication1"; string[] seprator = new string[] {"AA","Te" };
- Regex.split分
string value = "cat\r\ndog\r\nanimal\r\nperson"; // // Split the string on line breaks. // ... The return value from Split is a string[] array. // string[] lines = Regex.Split(value, "\r\n");
附加选项:
- StringSplitOptions.RemoveEmptyEntries
- StringSplitOptions.None
按空格分
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string s = "there is a cat"; string[] words = s.Split(' '); StringBuilder sb = new StringBuilder(); foreach (var item in words) { Console.WriteLine(item as string); sb.Append(item); } Console.WriteLine(sb); Console.ReadLine(); } } }
Regex.Split:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string value = "cat\r\ndog\r\nanimal\r\nperson"; string[] lines = Regex.Split(value, "\r\n"); foreach (var item in lines) { Console.WriteLine(item); } Console.ReadLine(); } } }
Output cat dog animal person
RemoveEmptyEntries:
using System; class Program { static void Main() { // // This string is also separated by Windows line breaks. // string value = "shirt\r\ndress\r\npants\r\njacket"; // // Use a new char[] array of two characters (\r and \n) to break // lines from into separate strings. Use "RemoveEmptyEntries" // to make sure no empty strings get put in the string[] array. // char[] delimiters = new char[] { '\r', '\n' }; string[] parts = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < parts.Length; i++) { Console.WriteLine(parts[i]); } // // Same as the previous example, but uses a new string of 2 characters. // parts = value.Split(new string[] { "\r\n" }, StringSplitOptions.None); for (int i = 0; i < parts.Length; i++) { Console.WriteLine(parts[i]); } } }
Output
(Repeated two times)
shirt
dress
pants
jacket
Sperate words:
using System; using System.Text.RegularExpressions; class Program { static void Main() { string[] w = SplitWords("That is a cute cat, man"); foreach (string s in w) { Console.WriteLine(s); } Console.ReadLine(); } /// <summary> /// Take all the words in the input string and separate them. /// </summary> static string[] SplitWords(string s) { // // Split on all non-word characters. // ... Returns an array of all the words. // return Regex.Split(s, @"\W+"); // @ special verbatim string syntax // \W+ one or more non-word characters together } }
Output That is a cute cat man
分路径:
using System; class Program { static void Main() { // The directory from Windows const string dir = @"C:\Users\Sam\Documents\Perls\Main"; // Split on directory separator string[] parts = dir.Split('\\'); //escape “\” foreach (string part in parts) { Console.WriteLine(part); } } }
Output C: Users Sam Documents Perls Main
执行效率:
// // Build long string. // _test = string.Empty; for (int i = 0; i < 120; i++) { _test += "01234567\r\n"; } // // Build short string. // _test = string.Empty; for (int i = 0; i < 10; i++) { _test += "ab\r\n"; } Methods tested: 100000 iterations static void Test1() { string[] arr = Regex.Split(_test, "\r\n", RegexOptions.Compiled); } static void Test2() { string[] arr = _test.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } static void Test3() { string[] arr = _test.Split(new string[] { "\r\n" }, StringSplitOptions.None);
结果:少量的字char[].split更快。For somewhat longer strings or files that contain more lines, Regex is appropriate.
Benchmark of Split on long strings [1] Regex.Split: 3470 ms [2] char[] Split: 1255 ms [fastest] [3] string[] Split: 1449 ms Benchmark of Split on short strings [1] Regex.Split: 434 ms [2] char[] Split: 63 ms [fastest] [3] string[] Split: 83 ms
在loop外分更好:
Slow version, before [C#] // // Split on multiple characters using new char[] inline. // string t = "string to split, ok"; for (int i = 0; i < 10000000; i++) { string[] s = t.Split(new char[] { ' ', ',' }); //loop内分 } Fast version, after [C#] // // Split on multiple characters using new char[] already created. // string t = "string to split, ok"; char[] c = new char[]{ ' ', ',' }; // <-- Cache this,loop外分 for (int i = 0; i < 10000000; i++) { string[] s = t.Split(c); }
File 操作:
File.ReadAllLines:
using System; using System.IO; class Program { static void Main() { int i = 0; foreach (string line in File.ReadAllLines("TextFile1.txt")) { string[] parts = line.Split(','); foreach (string part in parts) { Console.WriteLine("{0}:{1}", i, part); } i++; // For demo only } } }
Output 0:Dog 0:Cat 0:Mouse 0:Fish 0:Cow 0:Horse 0:Hyena 1:Programmer 1:Wizard 1:CEO 1:Rancher 1:Clerk 1:Farmer