首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::basic_string::c_str

const CharT* c_str() const;

返回指向以空结尾的字符数组的指针,其数据与字符串中存储的数据相等。

指针的范围[c_str(); c_str() + size()]是有效的,其中的值对应于字符串中存储的值,在最后一个位置之后有一个额外的空字符。

c_str()可因下列情况而失效:

  • 将对字符串的非Const引用传递给任何标准库函数,或
  • 调用字符串上的非Const成员函数,不包括operator[],,,at(),,,front(),,,back(),,,begin(),,,rbegin(),,,end()rend()...

写入通过c_str()是未定义的行为。

c_str() and data() perform the same function.

(since C++11)

参数

%280%29

返回值

指向基础字符存储的指针。

data()i == operator for every i in [0, size()).

(until C++11)

data() + i == &operator for every i in 0, size().

(since C++11)

复杂性

常量。

例外

(none)

(until C++11)

noexcept specification: noexcept

(since C++11)

注记

c_str()如果字符串对象不包含其他空字符,则只能将其视为指向空结束字符串的指针。

二次

代码语言:javascript
复制
#include <algorithm>
#include <cassert>
#include <cstring>
#include <string>
 
int main()
{
  std::string const s("Emplary");
  assert(s.size() == std::strlen(s.c_str()));
  assert(std::equal(s.begin(), s.end(), s.c_str()));
  assert(std::equal(s.c_str(), s.c_str() + s.size(), s.begin()));
  assert(0 == *(s.c_str() + s.size()));
}

二次

另见

front (C++11)

accesses the first character (public member function)

back (C++11)

accesses the last character (public member function)

data

returns a pointer to the first character of a string (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券