zoukankan      html  css  js  c++  java
  • stl学习之字符串

    其实string也是stl里面的内容,记录几点自己不常用的内容

    1.at方法(比[]会判断是否越位)

    2. int copy(char *s, int n, int pos=0) const; 

    把当前串中以pos开始的n个字符拷贝到以s为起始位置的字符数组中,返回实际拷贝的数目。注意要保证s所指向的空间足够大以容纳当前字符串,不然会越界

    3. string &erase(int pos=0, int n=npos);  //删除pos开始的n个字符,返回修改后的字符串

    4.void swap(string &s2);    //交换当前字符串与s2的值

    string与wstring的转换

    第一种方法

    调用Windows的API函数:WideCharToMultiByte()函数和MultiByteToWideChar()函数。

    第二种方法

    使用ATL的CA2W类与CW2A类。或使用A2W宏与W2A宏。

    第三种方法,跨平台的方法,使用CRT库的mbstowcs()函数和wcstombs()函数,需设定locale。

    以下是第三种方法的实现例子。

    //#pragma warning(disable: 4996)
    
    string ws2s(const wstring &ws)
    {
        string curLocale = setlocale(LC_ALL, NULL);  //curLocale="C";
        setlocale(LC_ALL, "chs");
        const wchar_t * _Source = ws.c_str();
        size_t _Dsize = 2 * ws.size() + 1;
        char * _Dest = new char[_Dsize];
        memset(_Dest, 0, _Dsize);
        wcstombs(_Dest, _Source, _Dsize);//wcstombs_s
        string result = _Dest;
        delete[] _Dest;
        setlocale(LC_ALL, curLocale.c_str());
        return result;
    }
    
    //string转成wstring
    wstring s2ws(const string &s)
    {
        string curLocale = setlocale(LC_ALL, NULL);    //curLocale = "C"
        setlocale(LC_ALL, "chs");
        const char *_Source = s.c_str();
        size_t _Dsize = s.size() + 1;
        wchar_t *_Dest = new wchar_t[_Dsize];
        wmemset(_Dest, 0, _Dsize);
        mbstowcs(_Dest, _Source, _Dsize);//mbstowcs_s
        wstring result = _Dest;
        delete[] _Dest;
        setlocale(LC_ALL, curLocale.c_str());
        return result;
    }
  • 相关阅读:
    ubuntu 搜索文件方法(find命令)
    tomcat ip访问
    Linux下tomcat 的启动 关闭 kill
    Hibernate 之 使用
    tar 用法
    ubuntu下配置django+apache+mysql+mod_python+Python
    Windows Mobile Ping 命令实现(转)
    C#异步方法调用(四大方法详解)
    HTML基础(一):HTML简介
    windows2003系统的iis不能下载exe文件
  • 原文地址:https://www.cnblogs.com/ultracpp/p/4099386.html
Copyright © 2011-2022 走看看