一、CString——Left、Right、Find、ReverseFind
CString——Left、Right、Find、ReverseFind
CString::Left(intnCount)
——返回字符串前nCount个字符的字符串
example:
CString str(_T("Shop,车间"));
str = str.Left(4);
结果:str="Shop";
CString::Right(int nCount)
——返回字符串后nCount个字符的字符串
example:
CString str(_T("Shop,车间"));
str = str.Right(2);
结果:str="车间";
CString::Find(_T(","))
返回“,”在字符串中的索引值
example:
CString str(_T("Shop,车间"));
int idex = str.Find(_T(","));
此时:idex=4;
宗:要想获得“,”右侧内容
str = str.Right(str.GetLength()-1-str.Find(_T(",")));
其中:
str.GetLength()=7;
-1排除“,”
-str.Find(_T(","))排除“,”前的所有字
CString::ReverseFind
int ReverseFind( TCHAR ch ) const;
返回值:
返回此CString对象中与要求的字符匹配的最后一个字符的索引;如果没有找到需要的字符则返回-1。
参数: ch 要搜索的字符。
说明:
此成员函数在此CString对象中搜索与一个子串匹配的最后一个字符。此函数类似于运行时函数strrchr。
示例:// CString::ReverseFind示例:
CString s( "abcabc" );
ASSERT( s.ReverseFind( 'b' ) == 4 );
二:char(wchar_t)与CString 之间相互转换
CString str;
char a[100];
//cstring->char
strcpy(a,str);
//char->cstring
str.format("%s",a);
//Cstring->wchar_t
wchar_t ss[MAX_PATH];
wcscpy(ss,strPath);
//wchar_t->cstring
str.format("%s",a);
补充:
c++标准库函数提供了字符和字符串的操作函数,并提供了其UNICODE版本,如:
char *strcpy(char *strDestination, const char *strSource);
wchar_t *wcscpy(wchar_t *strDestination, const wchar_t *strSource);
其中, wcscpy()即为strcpy()的宽字符版本,与_T的作用类似。
三、获取应用程序所在目录
转自:http://blog.csdn.net/whatday/article/details/7899724
第一种方法:
DWORD GetCurrentDirectory(
DWORD nBufferLength, // size, in characters, of directory buffer
LPTSTR lpBuffer // pointer to buffer for current directory
);
BOOL SetCurrentDirectory(
LPCTSTR lpPathName // pointer to name of new current directory
);
第二种方法
用GetModuleFileName得到应用程序的文件名(第一个参数为NULL)
再用_splitpath分析文件名得到路径
例如:
//得到当前路径
/*char buf[100];
GetCurrentDirectory(sizeof(buf),buf);
MessageBox(buf);
HINSTANCE hInst=NULL;
hInst=AfxGetApp()->m_hInstance;
char path_buffer[_MAX_PATH];
GetModuleFileName(hInst,path_buffer,sizeof(path_buffer));//得到exe文件的全路径
//分离路径和文件名。
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_splitpath( path_buffer, drive, dir, fname, ext );
CString Path;
Path.Format("%s%s",drive,dir);
char path[300];
strcpy(path,drive);
strcat(path,dir);
又或:
TCHAR exeFullPath[MAX_PATH];
CString strPath; //执行文件所在目录
GetModuleFileName(NULL,exeFullPath,MAX_PATH);
strPath=(CString)exeFullPath;
int position=strPath.ReverseFind('\\');
strPath=strPath.Left(position+1);
TCHAR FilePath[MAX_PATH]; //执行文件全路径,包括执行文件名
GetModuleFileName(NULL,FilePath,MAX_PATH);
(_tcsrchr(FilePath,'\\'))[1] = 0;
lstrcat(FilePath,_T("MY.exe"));
注意,对(_tcsrchr(FilePath,'\\'))[1] = 0; 这一句,其实这句可分解为两句话:
char *ch = _tcsrchr(szFilePath, _T('\\'));查找最后一个\出现的位置,并返回\后面的字符(包括\)
ch[1] = 0;//NULL 通过操作来操作szFilePath = 将szFilePath截断,截断最后一个\后面的字符(不包括\),注意,"\0”就等于0。
第三种方法:
VC中__argv[0]可以得到exe的程序名,然后用_splitpath可以分解得到程序路径。
第四种方法
#include<direct.h>
char buf[_MAX_PATH];
_getcwd(buf,_MAX_PATH);
第四种是得到操作系统所在的目录
char buf[100];
GetSystemDirectory(buf,100);
MessageBox(buf);
815



被折叠的 条评论
为什么被折叠?



