c++ string详解 c_str()

const char* c_str ( ) const;

将c++标准std string类转换为标准c的string格式 char * 类型,并将首地址返回, 地址从[0]开始算。

举例:

string testcstr = "Hello World";

const char *pch = testcstr.c_str();

cout<<pch<<endl;

cout<<pch[2]<<endl;

//打印结果为 Hello World

//l

 

char ch[20];

strcpy(ch, testcstr.c_str());

//strcpy需要 #include <string.h>

testat = "hahaha";

cout<<ch<<endl;

strcpy(ch, testcstr.c_str());

cout<<ch<<endl;

//打印结果为 Hello World

//hahaha

 

----------------------------------------

const char *c_str();c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同. 这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针 比如:最好不要这样: char* c; string s="1234"; c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理应该这样用: char c[20]; string s="1234"; strcpy(c,s.c_str()); 这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作再举个例子c_str() 以 char* 形式传回 string 内含字符串如果一个函数要求char*参数,可以使用c_str()方法: string s = "Hello World!";printf("%s", s.c_str()); //输出 "Hello World!"

 

----------------------------------------------------------------------------------

 

const char* c_str ( ) const;
Get C string equivalent

Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.

A terminating null character is automatically appended.

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only guaranteed to remain unchanged until the next call to a non-constant member function of the string object.

Parameters

none

Return Value

Pointer to an internal array containing the c-string equivalent to the string content.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main ()
{
  char * cstr, *p;

  string str ("Please split this phrase into tokens");

  cstr = new char [str.size()+1];
  strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  p=strtok (cstr," ");
  while (p!=NULL)
  {
    cout << p << endl;
// 将之前部分赋值为空, 并取得下一个标记点“ ”的地址
    p=strtok(NULL," ");
  }

  delete[] cstr;  
  return 0;
}



Output:

Please
split
this
phrase
into
tokens

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值