路过:string中的_cstr()、data()

来源:互联网 发布:模拟电网软件 编辑:程序博客网 时间:2024/06/05 08:03

_cstr()作用是吧一个string串转换成一个C-style的串,以"/0"null character结尾,返回的是一个指向该C-style串的常指针。

C-style的串的观看角度在于把串分成一个个字符的组合而成,比如str1="abcdef",转换成C-style串就是str1='a''b''c''d''e''f''/0';

对于标准库类型string串,则是在一个整体来看的,比如strcat(),strcpy()都是从中截取一个小整体串进行操作,结尾没有'/0'

【msdn上的一段代码,很好的说明了问题:】

// basic_string_c_str.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( )
{
   using namespace std;

   string  str1 ( "Hello world" );
   cout << "The original string object str1 is: "
        << str1 << endl;
   cout << "The length of the string object str1 = "
        << str1.length ( ) << endl << endl;

   // Converting a string to an array of characters
   const char *ptr1 = 0;
   ptr1= str1.data ( );
   cout << "The modified string object ptr1 is: " << ptr1
        << endl;
   cout << "The length of character array str1 = "
        << strlen ( ptr1) << endl << endl;

   // Converting a string to a C-style string
   const char *c_str1 = str1.c_str ( );
   cout << "The C-style string c_str1 is: " << c_str1
        << endl;
   cout << "The length of C-style string str1 = "
        << strlen ( c_str1) << endl << endl;
}

OUTPUT:

The original string object str1 is: Hello worldThe length of the string object str1 = 11The modified string object ptr1 is: Hello worldThe length of character array str1 = 11The C-style string c_str1 is: Hello worldThe length of C-style string str1 = 11
C风格字符串与标准库类型string性能比较(C-style character string and std::string)
《c++primer》上提到,推荐在c++程序中使用string,而不使用从C集成而来的风格字符串,原因如下:
(1)使用string安全,不用程序员管理内存分配释放
(2)程序写起来比较简洁、方便、不容易出错
(3)效率比较高
关于效率比较问题,书上有例子程序:
#include <iostream>  
#include <windows.h>
#include <string>
using   namespace std;

int main()  
{
    const size_t size = 20;   
    char pc[1000000];
   
    for (size_t i = 0; i != 10 - 1; ++i)
    {
        pc[i] = ' ';
    }
    pc[999999] = '/0';
   
    const size_t len = strlen(pc);
    size_t time = GetTickCount();
    for(size_t ix = 0; ix != size; ++ix)
    {
        char *pc2 = new char[len + 1];
        strcpy(pc2, pc);
        if (strcmp(pc2, pc))
        {       
            delete [] pc2;
        }
    }
   
    time = GetTickCount() - time;
    cout <<"C style time is: " <<time <<" ms." <<endl;
   
   
    string str (1000000, ' ');
    time = GetTickCount();
    for(int ix1 = 0; ix1 != size; ++ix1)
    {
        string str2 = str;
        if (str2 != str);
    }
    time = GetTickCount() - time;
    cout <<"C++ style time is: " <<time <<" ms." <<endl;

    return   0;
}  

运行结果:
c-style time is:93ms
c++ style time is:32ms

对于data(),很简单,他是string类的一个函数,作用是返回指向现有串的第一个字符的指针,看本页第一个msdn中的例子。