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() ) );
}

猜你喜欢

转载自blog.csdn.net/hsq1596753614/article/details/83180367
今日推荐