Open In App

std::string::data() in C++

The data() function writes the characters of the string into an array. It returns a pointer to the array, obtained from conversion of string to the array. Its Return type is not a valid C-string as no ‘\0’ character gets appended at the end of array.
Syntax:

const char* data() const;
char* is the pointer to the obtained array.
Parameters : None




// 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;
}

Output:



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

Here, we can easily notice, both contents and length of original string and transformed array are same.
If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.


Article Tags :
C++