data()函数将字符串的字符写入数组。它返回一个指向数组的指针,该指针是从字符串到数组的转换获得的。它的返回类型不是有效的C字符串,因为在数组末尾没有附加‘\ 0’字符。
句法:
const char* data() const;
char* is the pointer to the obtained array.
Parameters : None
- std :: 字符串:: 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
#include
#include
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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。