string自建常用函式(3)

enum eGET_SUBSTR_TYPE
{
eGET_SUBSTR_BEGIN, // 遇到token後,取得token之前的字串
eGET_SUBSTR_END, // 遇到token後,取得token之後的字串
eGET_SUBSTR_MAX,
};
enum eGET_SUBSTR_DIRECTION
{
eGET_SUBSTR_DIR_FORWARD, // 從字串前面開始找
eGET_SUBSTR_DIR_BACKWARD, // 從字串後面開始找
eGET_SUBSTR_DIR_MAX,
};

bool GetSubStrFromString(string& strSource, string strToken, string::size_type stPos, eGET_SUBSTR_TYPE eType, eGET_SUBSTR_DIRECTION eDirection); // 從字串中往eDirection方向取得stPos個strToken之前(或之後,依照eType而定)的剩餘字串


bool GetSubStrFromString(string& strSource, string strToken, string::size_type stPos, eGET_SUBSTR_TYPE eType, eGET_SUBSTR_DIRECTION eDirection)
{
if(stPos <= 0)
return false;
string::size_type stPos_ = string::npos, stPostmp_= 0;
if(eDirection == eGET_SUBSTR_DIR_FORWARD)
stPostmp_ = 0;
else if(eDirection == eGET_SUBSTR_DIR_BACKWARD)
stPostmp_ = string::npos;
string::iterator str_Iter_Begin, str_Iter_End, str_Iter_Pos;
str_Iter_Begin = strSource.begin();
str_Iter_End = strSource.end();
switch(eType)
{
case eGET_SUBSTR_BEGIN:
{
for(string::size_type stCounter = 0; stCounter < stPos; ++stCounter)
{
if(eDirection == eGET_SUBSTR_DIR_FORWARD)
stPostmp_ = strSource.find(strToken, stPostmp_);
else if(eDirection == eGET_SUBSTR_DIR_BACKWARD)
stPostmp_ = strSource.rfind(strToken, stPostmp_);
if(stPostmp_ == string::npos)
return false;
else
{
stPos_ = stPostmp_ + 1;
if(eDirection == eGET_SUBSTR_DIR_FORWARD)
++stPostmp_;
else if(eDirection == eGET_SUBSTR_DIR_BACKWARD)
--stPostmp_;
}
}
if(stPos_ != string::npos)
{
str_Iter_Begin += stPos_ - 1;
strSource.erase(str_Iter_Begin, str_Iter_End);
}
}
break;
case eGET_SUBSTR_END:
{
for(string::size_type stCounter = 0; stCounter < stPos; ++stCounter)
{
if(eDirection == eGET_SUBSTR_DIR_FORWARD)
stPostmp_ = strSource.find(strToken, stPostmp_);
else if(eDirection == eGET_SUBSTR_DIR_BACKWARD)
stPostmp_ = strSource.rfind(strToken, stPostmp_);
if(stPostmp_ == string::npos)
return false;
else
{
stPos_ = stPostmp_ + 1;
if(eDirection == eGET_SUBSTR_DIR_FORWARD)
++stPostmp_;
else if(eDirection == eGET_SUBSTR_DIR_BACKWARD)
--stPostmp_;
}
}
if(stPos_ != string::npos)
{
str_Iter_End -= strSource.size() - stPos_;
strSource.erase(str_Iter_Begin, str_Iter_End);
}
}
break;
}
return true;
}
使用方式舉例如下:
string strPath("C:\\WINDOWS\\system32\\hahaha.exe");
GetSubStrFromString(strPath, ".", 1, eGET_SUBSTR_BEGIN, eGET_SUBSTR_DIR_FORWARD);
// strPath == "C:\\WINDOWS\\system32\\hahaha"
GetSubStrFromString(strPath, "\\", 1, eGET_SUBSTR_END, eGET_SUBSTR_DIR_BACKWARD);
// strPath == "hahaha"

strPath = "C:\\WINDOWS\\system32\\hahaha.exe";
GetSubStrFromString(strPath, "\\", 3, eGET_SUBSTR_BEGIN, eGET_SUBSTR_DIR_BACKWARD);
// strPath == "c:"
posted on 2008-10-29 10:59 LancetChang 阅读(228) 评论(0) 收藏 举报


浙公网安备 33010602011771号