请高手指教高效的Split函数

本文对比了C++与C#中字符串分割功能的实现方式及性能。通过相同的字符串分割任务,在同等条件下,C#表现出明显更快的速度。作者寻求更高效的C++字符串分割方法,并提出使用汇编语言可能提升性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /**C++实现*/   

//String继承于std::string  
      
//我的Split代码,vector操作很慢啊。 
                
typedef vector
<String> Strings;  
 
Strings Split(
char* by,bool havenull=true)  
{   
    Strings strs;    
    typedef unsigned 
int UINT;   
    UINT bylen
=strlen(by);   
    UINT start
=0;   
    UINT pos
=0;   
    
char* head=(char*)this->c_str();   
    
if(havenull)   
    {   
        
while((pos=this->find(by,start))!=-1)   
        {   
            
*(head+pos)=0;   
            strs.push_back(head
+start);   
            
*(head+pos)=*by;   
            start
=pos+bylen;   
        };   
    }   
    
else   
    {   
        
while((pos=this->find(by,start))!=-1)   
        {   
            
if(pos-start>0)                                       
            {   
                
*(head+pos)=0;   
                strs.push_back(head
+start);   
                
*(head+pos)=*by;   
            };   
            start
=pos+bylen;   
        };   
    };   
    
if(start<this->size())   
    {   
        strs.push_back(
this->substr(start,this->size()-start));   
    };   
    
return strs;   
};   
//测试代码:   
void main()   
{   
    String s;   
    Strings ok;   
    s
="/c:;lihdaofhdo/al;jdf;lkajdf/adlfkadfj;ajdqwer/asdfja;ldsjqwerq/difjtt.cpp//";   
    
for(int j=0;j<1000000;j++)   
        ok
=s.Split("/",false);   
    
for(int i=0;i<ok.size();i++)   
    {   
        cout
<<ok[i]<<endl;   
    };   
};   
           
    
/**C#实现的代码*/   
    
using System;   
    
using System.Collections.Generic;   
    
using System.Text;   
       
    
namespace ConsoleApplication1   
    {   
        
class Program   
        {   
            
static void Main(string[] args)   
            {   
                String a 
="/c:;lihdaofhdo/al;jdf;lkajdf/adlfkadfj;ajdqwer/asdfja;ldsjqwerq/difjtt.cpp//";   
                
string s = "/";   
                
char[] by = s.ToCharArray();   
                String [] strs;   
                Console.ReadKey();   
               strs 
= a.Split(by);   
               
for (int j = 0; j < 1000000; j++)   
                {   
                   strs 
= a.Split(by);   
               };   
               
for (int i = 0; i < strs.Length; i++)   
               {   
                   Console.WriteLine(strs[i]);   
               };   
                Console.ReadKey();   
           }   
       }   
    }   

//测试机器CPU:AMD64 3000+ ,操作系统Windows XPSP2。   
//都执行字符串切分一百万次,这时C#的不到一秒完成,C++打开优化要六秒的样子。
//哪位大侠知道高效的C++下Split代码?嵌入汇编完成应该会快点。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值