basic_string::c_str()是C++中的内置函数,该函数返回一个指向数组的指针,该数组包含一个空终止的字符序列,这些序列表示basic_string对象的当前值。此数组包含组成basic_string对象值的相同字符序列,最后还有一个额外的终止null-character。
用法:
const CharT* c_str() const
参数:该函数不接受任何参数。
返回值:该函数返回一个以Null结尾的常量指针,该指针指向字符串的字符数组存储。
下面是上述函数的实现:
示例1:
// C++ code for illustration of
// basic_string::c_str function
#include <bits/stdc++.h>
#include <string>
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 <bits/stdc++.h>
#include <string>
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++ div()用法及代码示例
- C++ fma()用法及代码示例
- C++ log()用法及代码示例
- C++ map key_comp()用法及代码示例
- C++ map rend()用法及代码示例
- C++ map rbegin()用法及代码示例
- C++ map rbegin()用法及代码示例
- C++ real()用法及代码示例
- C++ imag()用法及代码示例
注:本文由纯净天空筛选整理自AdityaTiwari5大神的英文原创作品 basic_string c_str function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。