1. 程式人生 > >C++中路徑字串的切割方法

C++中路徑字串的切割方法

在開發中,我們經常需要得到當前模組的上級目錄,甚至上上級目錄等,下面提供一個例項演示當前模快路徑的獲取、通過路徑字串的切割獲取上三級目錄。
【詳細程式碼】

#include <iostream>
#include <atlstr.h>
#include <string>
using namespace std;

string CString2string(CString cstr)
{
	USES_CONVERSION;
	return W2A(cstr.GetBuffer());
}
int main()
{
	// 得到當前模組路徑
	CString path;
	GetModuleFileName(NULL, path.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
	path.ReleaseBuffer();
	cout << CString2string(path) << endl;
	// 得到當前模快的上三級路徑
	int pos = 0;
	for (int i = 0; i < 3; i++)
	{
		pos = path.ReverseFind('\\');//反向查詢,返回路徑字串中“\”字元最後一次出現的索引值
		path = path.Left(pos);//取索引值以左的子字串
	}
	cout << CString2string(path) << endl;
	system("pause");
	return 0;
}

【程式碼執行結果】
在這裡插入圖片描述
【舉一反三】
(1)與ReverseFind(In XCHAR ch) 方法對應的方法是FindOneOf(In_z PCXSTR pszCharSet),這兩個方法都定義在cstringt.h中,下面是兩個方法的定義:

// Find the first occurrence of any of the characters in string 'pszCharSet'
int FindOneOf(_In_z_ PCXSTR pszCharSet) const throw()
{
	ATLASSERT( AtlIsValidString( pszCharSet ) );
	PCXSTR psz = StringTraits::StringScanSet( GetString(), pszCharSet );
	return( (psz == NULL) ? -1 : int( psz-GetString() ) );
}

// Find the last occurrence of character 'ch'
int ReverseFind(_In_ XCHAR ch) const throw()
{
	// find last single character
	PCXSTR psz = StringTraits::StringFindCharRev( GetString(), ch );
	// return -1 if not found, distance from beginning otherwise
	return( (psz == NULL) ? -1 : int( psz-GetString() ) );
}

(2)與Left(In int nCount)對應的方法是Right(In int nCount),這兩個方法都定義在cstringt.h中,下面是兩個方法的定義:

// Return the substring consisting of the rightmost 'nCount' characters
CStringT Right(_In_ int nCount) const
{
	// nCount is in XCHARs
	if (nCount < 0)
		nCount = 0;

	int nLength = GetLength();
	if( nCount >= nLength )
	{
		return( *this );
	}

	return( CStringT( GetString()+nLength-nCount, nCount, GetManager() ) );
}

// Return the substring consisting of the leftmost 'nCount' characters
CStringT Left(_In_ int nCount) const
{
	// nCount is in XCHARs
	if (nCount < 0)
		nCount = 0;

	int nLength = GetLength();
	if( nCount >= nLength )
	{
		return( *this );
	}
	
	return( CStringT( GetString(), nCount, GetManager() ) );
}