The basic_string c_str function in C++ STL?


The basic_string c_str function that returns a pointer to an array of characters that is terminated using null character. It is an inbuilt method that has the value of a string that has null character termination.

Syntax to define a c_str function in C++ −

const Char ptr* c_str() const

About the function

It is an inbuilt method for the c++ STL library. No parameters can be passed to the method. It returns a char pointer. This pointer points to NULL terminated character array.

Example

 Live Demo

#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";
   }
}

Output

Checking if the string I Love Tutorials Point contains P
The string contains character

Updated on: 04-Oct-2019

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements