C++string 에서 문자열 을 자 르 는 방법 을 자세히 설명 합 니 다.
find(string strSub, npos);
find_last_of(string strSub, npos);
그 중에서 strSub 는 찾 아야 할 하위 문자열 입 니 다.npos 는 시작 위 치 를 찾기 위해 서 입 니 다.하위 문자열 이 처음 나타 난 위 치 를 되 돌려 줍 니 다.그렇지 않 으 면-1 을 되 돌려 줍 니 다.주:
(1)find_last_of 의 npos 는 끝 에서 부터 찾 을 수 있 는 위치 입 니 다.
(2)다음 글 에 사용 되 는 strsub(npos,size)함수 입 니 다.그 중에서 npos 는 시작 위치 이 고 size 는 캡 처 크기 입 니 다.
예 1:문자열 에 어떤 문자열 이 있 는 지 직접 찾 습 니 다("2"를 되 돌려 줍 니 다)
std::string strPath = "E:\\ \\2018\\2000 \\a.shp"
int a = 0;
if (strPath.find("2018") == std::string::npos)
{
a = 1;
}
else
{
a = 2;
}
return a;
예 2:어떤 문자열 의 문자열 을 찾 습 니 다.("E:"를 되 돌려 줍 니 다.)
std::string strPath = "E:\\ \\2018\\2000 \\a.shp"
int nPos = strPath.find("\\");
if(nPos != -1)
{
strPath = strPath.substr(0, nPos);
}
return strPath;
예 3:어떤 문자열 의 두 문자열 사이 의 문자열 을 찾 습 니 다("2000 좌표계"로 돌아 갑 니 다)
std::string strPath = "E:\\ \\2018\\2000 \\a.shp"
std::string::size_type nPos1 = std::string::npos;
std::string::size_type nPos2 = std::string::npos;
nPos1 = strPath.find_last_of("\\");
nPos2 = strPath.find_last_of("\\", nPos1 - 1);
if(nPos1 !=-1 && npos2 != -1)
{
strPath = strPath.substr(nPos2 + 1, nPos1 - nPos2 - 1);
}
return strPath;
향상:경로 이름 의 하위 디 렉 터 리 를 재 귀적 으로 가 져 옵 니 다.
// :strPath ,strSubPath ,
nSearch ( 1 )
bool _GetSubPath(std::string& strPath,std::string& strSubPath, int nSearch)
{
if (-1 == nSearch || strPath.empty())
return false;
std::string::size_type nPos1 = std::string::npos;
nPos1 = strPath.find_last_of("\\");
if (nPos1 != -1)
{
strSubPath = strPath.substr(nPos1 + 1, strPath.length() - nPos1);
int nNewSearch = nSearch > 1 ? nSearch - 1 : -1;
_GetSubPath(strPath.substr(0, nPos1), strSubPath, nNewSearch);
}
return true;
}
int main()
{
std::string strPath = "E:\\ \\2018\\2000 \\a.shp";
std::string strSubPath = "";
if(_GetSubPath(strPath, strSubPath, 1)
{
printf(“ 'a.shp'”);
}
if(_GetSubPath(strPath, strSubPath, 2)
{
printf(“ '2000 '”);
}
}
위 에서 말 한 것 은 소 편 이 소개 한 C+string 에서 자주 사용 하 는 문자열 을 캡 처 하 는 방법 으로 상세 하 게 통합 하 는 것 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!