C++ string commonly used to intercept string methods

  • 2020-06-15 10:03:33
  • OfStack

There are many common methods for string to intercept strings, but the following two methods can meet the requirements:

find(string strSub, npos);

find_last_of(string strSub, npos);

Where strSub is the substring to be looked for, and npos is the starting position of the search. Find the first occurrence of the return substring, otherwise return -1;

Note:

(1) The npos of find_last_of is the position sought from the end.

(2) strsub(npos, size) function used below, where npos is the starting position and size is the interception size

Example 1: Find a string directly in the string (return "2")


std::string strPath = "E:\\ data \\2018\\2000 Coordinate system \\a.shp"
int a = 0; 
if (strPath.find("2018") == std::string::npos)
{
	a = 1;
}
else
{
	a = 2;
}
return a;

Example 2: Looking for a string string (return "E:")


std::string strPath = "E:\\ data \\2018\\2000 Coordinate system \\a.shp"
int nPos = strPath.find("\\");
if(nPos != -1)
{
  strPath = strPath.substr(0, nPos);
}
return strPath;

Example 3: Find the string between two substrings in a string (return "2000 coordinate system")


std::string strPath = "E:\\ data \\2018\\2000 Coordinate system \\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;

Improved: Recursively retrieves subdirectories in path names


// Gets a subdirectory in the pathname :strPath Is the path name, strSubPath Is the output subdirectory, 
 nSearch For the level retrieved from the tail forward ( The default is 1 level )
 
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:\\ data \\2018\\2000 Coordinate system \\a.shp";
  std::string strSubPath = "";
  if(_GetSubPath(strPath, strSubPath, 1)
  {
    printf( "Return 'a.shp' " );
  }
  if(_GetSubPath(strPath, strSubPath, 2)
  {
    printf( "Return '2000 Coordinate system ' " );
  }
}

Related articles: