ฟังก์ชัน c_str() ของ basic_string คืนค่า pointer ไปยังอาร์เรย์ตัวอักษรที่จบด้วย null character เป็นเมธอดในตัว (built-in) ของ C++ STL
ไวยากรณ์
const Char ptr* c_str() const
รายละเอียด
ไม่มีพารามิเตอร์ คืนค่า char pointer ชี้ไปยัง character array ที่จบด้วย NULL
ตัวอย่าง
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main() {
string s = "I Love Tutorials Point";
int flag = 0;
cout<<"Checking if the string "<<s<<" contains P "<<endl;
for(int i = 0; i < s.size(); i++) {
if(s.c_str()[i] == 'P') {
cout<<"The string contains character";
flag = 1;
}
}
if(flag == 0) {
cout<<"The string does not contains character";
}
}
ผลลัพธ์
Checking if the string I Love Tutorials Point contains P The string contains character