basic_string c_str function in C++ STL

The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end.

Syntax:

const CharT* c_str() const

Parameter: The function does not accept any parameter.



Return Value : The function returns a constant Null terminated pointer to the character array storage of the string.

Below is the implementation of the above function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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());
}

chevron_right


Output:

s1.size is equal to strlen(s1.c_str()) 
GeeksForGeeks 

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
    }
}

chevron_right


Output:

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.