string自建常用函式(2)

const char SLASH[] = "\\";

string GetFileNameFromPath(string); // 將路徑傳入,傳出最後一個目錄(或檔案名稱)


string GetFileNameFromPath(string strPath_)
{
    
string::size_type stPos_ = 0,  stPostmp_= strPath_.size();
    
string::iterator str_Iter_Begin, str_Iter_End, str_Iter_Pos;
    str_Iter_Begin 
= strPath_.begin();
    str_Iter_End 
= strPath_.end();

    stPostmp_ 
= strPath_.rfind(SLASH, stPostmp_);
    
if(stPostmp_ == string::npos)
        
return strPath_;
    
else
        stPos_ 
= stPostmp_ + 1;

    
if(stPos_ != 0)
    
{
        str_Iter_End 
-= strPath_.size() - stPos_;

        strPath_.erase(str_Iter_Begin, str_Iter_End);
    }


    
return strPath_;
}

 

使用方式舉例如下:

 

string strPath("C:\\WINDOWS\\system32\\notepad.exe");

string strFilePath = GetFileNameFromPath(strPath);

// strFilePath == "notepad.exe"


strPath(
"C:\\WINDOWS\\system32");

strFilePath 
= GetFileNameFromPath(strPath);

// strFilePath == "system32"

posted on 2008-10-29 10:26  LancetChang  阅读(138)  评论(0)    收藏  举报

导航