ST::String:C++中的数据()

函数的作用是:将字符串中的字符写入数组。它返回一个指向数组的指针,该指针是从字符串到数组的转换中获得的。其返回类型不是有效的C字符串 “不” 字符被追加到数组的末尾。 语法:

null
const char* data() const;
char* is the pointer to the obtained array.
Parameters : 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

在这里,我们很容易注意到,原始字符串和转换数组的内容和长度都是相同的。 本文由 萨希·提瓦里 .如果你喜欢极客(我们知道你喜欢!)如果你想投稿,你也可以用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享