软讯网络 > 编程语言 > C/C++ > 请高手指教高效的Split函数
【标 题】:请高手指教高效的Split函数
【关键字】:
Split
【来 源】:http://blog.csdn.net/suxiaojack/archive/2006/08/23/1109053.aspx
请高手指教高效的Split函数
1 /**C++实现*/
2 //String继承于std::string
3 //我的Split代码,vector操作很慢啊。
4
5 typedef vector<String> Strings;
6 Strings Split(char* by,bool havenull=true)
7 {
8 Strings strs;
9 typedef unsigned int UINT;
10 UINT bylen=strlen(by);
11 UINT start=0;
12 UINT pos=0;
13 char* head=(char*)this->c_str();
14 if(havenull)
15 {
16 while((pos=this->find(by,start))!=-1)
17 {
18 *(head+pos)=0;
19 strs.push_back(head+start);
20 *(head+pos)=*by;
21 start=pos+bylen;
22 };
23 }
24 else
25 {
26 while((pos=this->find(by,start))!=-1)
27 {
28 if(pos-start>0)
29 {
30 *(head+pos)=0;
31 strs.push_back(head+start);
32 *(head+pos)=*by;
33 };
34 start=pos+bylen;
35 };
36 };
37 if(start<this->size())
38 {
39 strs.push_back(this->substr(start,this->size()-start));
40 };
41 return strs;
42 };
43 //测试代码:
44 void main()
45 {
46 String s;
47 Strings ok;
48 s="\\c:;lihdaofhdo\\al;jdf;lkajdf\\adlfkadfj;ajdqwer\\asdfja;ldsjqwerq\\difjtt.cpp\\\\";
49 for(int j=0;j<1000000;j++)
50 ok=s.Split("\\",false);
51 for(int i=0;i<ok.size();i++)
52 {
53 cout<<ok[i]<<endl;
54 };
55 };
56
57 /**C#实现的代码*/
58 using System;
59 using System.Collections.Generic;
60 using System.Text;
61
62 namespace ConsoleApplication1
63 {
64 class Program
65 {
66 static void Main(string[] args)
67 {
68 String a ="\\c:;lihdaofhdo\\al;jdf;lkajdf\\adlfkadfj;ajdqwer\\asdfja;ldsjqwerq\\difjtt.cpp\\\\";
69 string s = "\\";
70 char[] by = s.ToCharArray();
71 String [] strs;
72 Console.ReadKey();
73 strs = a.Split(by);
74 for (int j = 0; j < 1000000; j++)
75 {
76 strs = a.Split(by);
77 };
78 for (int i = 0; i < strs.Length; i++)
79 {
80 Console.WriteLine(strs[i]);
81 };
82 Console.ReadKey();
83 }
84 }
85 }
86 //测试机器CPU:AMD64 3000+ ,操作系统Windows XPSP2。
87 //都执行字符串切分一百万次,这时C#的不到一秒完成,C++打开优化要六秒的样子。
哪位大侠知道高效的C++下Split代码?嵌入汇编完成应该会快点。