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;

}

 

你可能感兴趣的:(字符串)