当前位置:C++技术网 > 资讯 > VS实战理解CString与String转换

VS实战理解CString与String转换

更新时间:2018-12-18 18:17:18浏览次数:1+次

今天我们实际写个小程序来理解CString与String之间的转换,因为我不喜欢什么一大堆的讲解,还不用得上,实际操作时会出现很多我们预料不到的错误,这实在是亲身体验啊!很多东西还是直接上例子讲解的好。

我们基于对话框来实现字符串翻转。我们在编辑框中输入字符串,点击“清除”按钮,清空字符串,点击“翻转”按钮实现翻转。
为这两个按钮建立消息响应函数,为编辑框关联空间变量m_nStr。

void CMFCApplication3Dlg::OnClickedClear()
{
    CString ClearStr;
    m_nStr.GetWindowTextW(ClearStr);
    ClearStr.Delete(0, ClearStr.GetLength());
    //m_nStr.SetWindowTextW("");
    std::string str1 = "";
    CString strstr(str1.c_str());
    m_nStr.SetWindowTextW(strstr);/////将字符串清空
}
void CMFCApplication3Dlg::OnClickedFanzhuan()
{
    CString DealStr;
    m_nStr.GetWindowTextW(DealStr);//得到编辑框的字符串
    CStringA stra(DealStr.GetBuffer(0));
    DealStr.ReleaseBuffer();
    std::string str = stra.GetBuffer(0);
    int len = str.length();
    for (int j = 0; j<len / 2; j++)
    {
        //前后交换
        char temp = str[j];
        str[j] = str[len - j - 1];
        str[len - j - 1] = temp;
    }
    CString cstr(str.c_str());
    m_nStr.SetWindowTextW(cstr);
}


    对于翻转程序我没有用函数来实现,有点棘手,你自己可以试试哦!在项目里,没有C++的头文件等。但我们这里用到了,因此你需要自己添加上。我们看看这里需要用到的头文件(或许头文件有些用不上):

#include "algorithm"
#include "iostream"
#include "vector"
using namespace std;

    我就解释下第二个函数,你懂了第二个函数就懂了第一个函数,也就懂了类型转换。

首先我们得到编辑框的字符串,调用函数GetBuffer转化为ANSI编码,但是要记得释放哦!在VS里是Unicode我们在调用GetBuffer转换为string类型,最后就是简单的算法实现翻转了