C++ 字串庫 - data



描述

它返回一個指向陣列的指標,該陣列包含一個以 null 結尾的字元序列(即 C 字串),表示字串物件的當前值。

宣告

以下是 std::string::data 的宣告。

const char* data() const;

C++11

const char* data() const noexcept;

C++14

const char* data() const noexcept;

引數

返回值

它返回一個指向陣列的指標,該陣列包含一個以 null 結尾的字元序列(即 C 字串),表示字串物件的當前值。

異常

如果丟擲異常,字串不會發生任何更改。

示例

以下為 std::string::data 的示例。

#include <iostream>
#include <string>
#include <cstring>

int main () {
   int length;

   std::string str = "sairamkrishna mammahe";
   char* cstr = "sairamkrishna mammahe";

   if ( str.length() == std::strlen(cstr) ) {
      std::cout << "str and cstr have the same length.\n";

      if ( memcmp (cstr, str.data(), str.length() ) == 0 )
         std::cout << "str and cstr have the same content.\n";
   }
  return 0;
}

示例輸出應如下所示:

str and cstr have the same length.
str and cstr have the same content.  
string.htm
廣告

© . All rights reserved.