当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。