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() ) );
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值