basic_string :: c_str()是C++中的内置函数,它返回一个指向数组的指针,该数组包含一个以null终止的字符序列,这些字符代表了basic_string对象的当前值。此数组包含组成basic_string对象值的相同字符序列,最后还有一个额外的终止空字符。
句法:
const CharT* c_str() const
参数:该函数不接受任何参数。
返回值:该函数返回一个以Null终止的常量指针,该指针指向字符串的字符数组存储。
下面是上述函数的实现:
程序1:
// C++ code for illustration of
// basic_string::c_str function
#include
#include
using namespace std;
int main()
{
// declare a example string
string s1 = "GeeksForGeeks";
// check if the size of the string is same as the
// size of character pointer given by c_str
if (s1.size() == strlen(s1.c_str())) {
cout << "s1.size is equal to strlen(s1.c_str()) " << endl;
}
else {
cout << "s1.size is not equal to strlen(s1.c_str())" << endl;
}
// print the string
printf("%s \n", s1.c_str());
}
输出:
s1.size is equal to strlen(s1.c_str())
GeeksForGeeks
程式2:
// C++ code for illustration of
// basic_string::c_str function
#include
#include
using namespace std;
int main()
{
// declare a example string
string s1 = "Aditya";
// print the characters of the string
for (int i = 0; i < s1.length(); i++) {
cout << "The " << i + 1 << "th character of string " << s1
<< " is " << s1.c_str()[i] << endl;
}
}
输出:
The 1th character of string Aditya is A
The 2th character of string Aditya is d
The 3th character of string Aditya is i
The 4th character of string Aditya is t
The 5th character of string Aditya is y
The 6th character of string Aditya is a
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。