當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ std::string::data()用法及代碼示例


data()函數將字符串的字符寫入數組。它返回一個指向數組的指針,該指針是從字符串到數組的轉換獲得的。它的Return類型不是有效的C-string,因為在數組末尾沒有附加'\ 0'字符。句法:

const char* data() const;
char* is the pointer to the obtained array.
參數: None
  • std::string::data()返回該字符串擁有的數組。因此,調用者不得修改或釋放內存。
    讓我們舉一個例子,其中ptr指向最終數組。
    ptr[2] = 'a';
    this will raise an error as ptr points to an array that
    is owned by the string, in other words ptr is now pointing
    to constant array and assigning it a new value is now not allowed.
    
  • data()的返回值僅在下一次針對同一字符串的非常量成員函數的調用之前才有效。
    說明:
    假設,str是需要在數組中轉換的原始字符串
    // converts str in an array pointed by pointer ptr.
    const char* ptr = str.data(); 
    
    // Bad access of str after modification
    // of original string to an array
    str += "hello"; // invalidates ptr
    
    // Now displaying str with reference of ptr
    // will give garbage value
    cout << ptr; // Will give garbage value
    
// CPP code to illustrate 
// std::string::data() 
   
#include <iostream> 
#include <string> 
#include <cstring> 
using namespace std; 
   
// Function to demonstrate data()  
void dataDemo(string str1) 
{ 
    // Converts str1 to str2 without appending 
    // '/0' at the end 
    const char* str2; 
    str2 = str1.data(); 
      
    cout << "Content of transformed string:"; 
    cout << str2 << endl; 
   
    cout << "After data(), length:"; 
    cout << strlen(str2); 
      
      
} 
          
// Driver code 
int main() 
{ 
    string str("GeeksforGeeks"); 
   
    cout << "Content of Original String:"; 
    cout << str << endl; 
    cout << "Length of original String:"; 
    cout << str.size() << endl; 
     
    dataDemo(str); 
   
    return 0; 
}

輸出:

Content of Original String:GeeksforGeeks
Length of original String:13
Content of transformed string:GeeksforGeeks
After data(), length:13


相關用法


注:本文由純淨天空篩選整理自 std::string::data() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。