c++ string中的c_str()与data()用法

#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 world
The length of the string object str1 = 11

The modified string object ptr1 is: Hello world
The length of character array str1 = 11

The C-style string c_str1 is: Hello world
The length of C-style string str1 = 11

解释:

1.const char*   string::c_str   () const:

(1)Returns the   contents   of the   string   as a   C-string   (an array   of   characters that   has   the null   character   '\0 ' appended).

 

(2)The return   value   is owned   by   the string.   Thus,   the caller   must   neither modify   nor   free or   delete   the return   value.

 

(3)The return   value   is valid   only   as long   as   the string   exists,   and as   long   as  only   constant  functions  are   called  for  it.

 

 

2.const char*   string::data   () const

(1)Returns the   contents   of the   string   as a   character   array.

 

(2)The return   value   contains all   characters   of the   string   without any   modification   or extension.   In   particular, no   null   character is   appended.   Thus, the   return   value is,   in   general, not   a   valid C-string.

 

(3)The return   value   is owned   by   the string.   Thus,   the caller   must   neither modify   nor   free or   delete   the return   value.

 

(4)The return   value   is valid   only   as long   as   the string   exists,   and as   long   as only   constant   functions are   called   for it.

 

实际上两个函数完全一致。并不会补\0。

#include <iostream>
#include <string>

using namespace std;

int main(){
    string a = "test";
    a[4] = 'a';
    a[5] = 'b';
    const char* b = a.c_str();
    const char* c = a.data();
    cout << a << endl << b << endl << c;
}
 

结果是:

test
testab
testab

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值