字符串清理

       在公共函數中,發現如下一個刪除字符串中的換行回車符的函數

string DelStringEnter(string& str)
{
    string::size_type loc = str.find( "\n", 0 );
    
    while( loc!=string::npos )
    {
        str.erase(loc,1);
        loc=str.find( "\n", 0 );
    }
    
    loc = str.find( "\r", 0 );
    
    while( loc!=string::npos )
    {
        str.erase(loc,1);
        loc=str.find( "\r", 0 );
    }
    return str;
}


這種方法真的很爛,達到O(n^2)的複雜度

其實有更好的算法,可以達到O(n)複雜度

 

string DelStringEnter(string& str)                                                              
{                                                                                               
    string::size_type c = 0;                                                                    
    for(string::iterator it=str.begin();it<str.end();it++)                                      
    {                                                                                           
        if( *it == '\r' || *it == '\n' )                                                        
        {                                                                                       
            c++;                                                                                
        }                                                                                       
        else                                                                                    
        {                                                                                       
           *(it - c) = *it;                                                                     
        }                                                                                       
    }                                                                                           
    //尾部長度爲c的串都是無效的                                                   
    str.erase(str.size()-c-1,c);                                                                
    return str;                                                                                 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章