当 VC不使用MFC,无法使用属于MFC的CString,为此自定义一个,先暂时使用,后续完善。
头文件:
#pragma once #define MAX_LOADSTRING 100 // 最大字符数 class CString { public: char *c_str, cSAr[MAX_LOADSTRING]; WCHAR *w_str, wSAr[MAX_LOADSTRING]; void operator = (const char *str); // = 操作,获得c字符串: str = "sss"; 式样 void operator + (const CString str); // + 操作,获得s字符串加: s1 = s2 + s3; 式样 void operator += (const CString str); // += 操作,获得s字符串加: s1 += "s2"; 式样 int StrCount(void);// 返回字符串长度s.StrCount() CString(void); private: int iStrCount; // 字符串数量 void CharToWChar(const char *pChar);//窄字符转宽字符 void WCharToChar(WCHAR *pWideChar);//宽字符转窄字符 };
C文件:
#include "stdafx.h" #include "String.h" CString::CString(void) { c_str = cSAr; w_str = wSAr; } void CString::operator = (const char *str) // = { if(str == NULL) return; iStrCount = strlen(str);//获取字符串长度 for(int i = 0; i < iStrCount; i++)//转内存储 cSAr[i] = str[i]; cSAr[iStrCount] = 0; CharToWChar(str);//转宽字符 } void CString::operator + (const CString str) // + { // } void CString::operator += (const CString str) // += { // } int CString::StrCount(void) { return iStrCount; } void CString::CharToWChar(const char *pChar)//窄字符转宽字符 { if(pChar == NULL) return; int needWChar = MultiByteToWideChar(CP_ACP, 0, pChar, -1, NULL, 0); if(needWChar > 0) { ZeroMemory(wSAr, (needWChar + 1) * sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, pChar, -1, wSAr, needWChar); } } void CString::WCharToChar(WCHAR *pWideChar)//宽字符转窄字符 { if(pWideChar == NULL) return; int needBytes = WideCharToMultiByte(CP_ACP, 0, pWideChar, -1, NULL, 0, NULL, NULL); if(needBytes > 0) { ZeroMemory(cSAr, (needBytes + 1) * sizeof(char)); WideCharToMultiByte(CP_ACP, 0, pWideChar, -1, cSAr, needBytes, NULL, NULL); } }