自定义字符类

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

 

转载于:https://www.cnblogs.com/hbg200/p/9176945.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值