char* vs std:string vs char[] in C++ - GeeksforGeeks

30 Mar, 2022
In this article, we are going to inspect three different ways of initializing strings in C++ and discuss differences between them.
1. Using char*
Here, str is basically a pointer to the (const)string literal.Syntax:
char* str = "This is GeeksForGeeks";
Pros:
Only one pointer is required to refer to whole string. That shows this is memory efficient.No need to declare the size of string beforehand.
Only one pointer is required to refer to whole string. That shows this is memory efficient.
No need to declare the size of string beforehand.
CPP
// CPP program to illustrate *char#include <iostream>using namespace std;  int main(){    // pointer str points to const string literal "Hello".    // No need to declare size.    char* str1 = "This is GeeksForGeeks";      cout << str1 << endl;      int size = 30;      // can allocate size dynamically.    char* str2 = (char*)malloc(sizeof(char) * size);      str2 = "GeeksForGeeks For Everyone";      cout << str2;      return 0;}
This is GeeksForGeeks
GeeksForGeeks For Everyone
Cons:
This works fine in C but writing in this form is a bad idea in C++. That’s why compiler shows warningof “deprecated conversion from string constant to ‘char*'” because in C string literals are arrays of char butin C++ they are constant array of char. Therefore use const keyword before char*.const char* str = "This is GeeksForGeeks";We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str. Refer storage-for-strings-in-c for more detail.CPPCPP// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std;  int main(){    // This initialization gives warning in C++.    // "deprecated conversion from string constant    // to 'char*'"    char* str = "Hello";      const char* str1 = "Hello"; // No warning      // trying to modify const string literal    // gives Runtime error    str[1] = 'o';      cout << str << endl;      return 0;}Output:Segmentation Fault
This works fine in C but writing in this form is a bad idea in C++. That’s why compiler shows warningof “deprecated conversion from string constant to ‘char*'” because in C string literals are arrays of char butin C++ they are constant array of char. Therefore use const keyword before char*.const char* str = "This is GeeksForGeeks";
const char* str = "This is GeeksForGeeks";
We cannot modify the string at later stage in program. We can change str to point something else but cannot change value present at str. Refer storage-for-strings-in-c for more detail.CPPCPP// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std;  int main(){    // This initialization gives warning in C++.    // "deprecated conversion from string constant    // to 'char*'"    char* str = "Hello";      const char* str1 = "Hello"; // No warning      // trying to modify const string literal    // gives Runtime error    str[1] = 'o';      cout << str << endl;      return 0;}Output:Segmentation Fault
CPP
// CPP program to illustrate assigning// *char value to other variable #include <iostream>using namespace std;  int main(){    // This initialization gives warning in C++.    // "deprecated conversion from string constant    // to 'char*'"    char* str = "Hello";      const char* str1 = "Hello"; // No warning      // trying to modify const string literal    // gives Runtime error    str[1] = 'o';      cout << str << endl;      return 0;}
Segmentation Fault
2. Using std::string
Syntax:
std::string str = "This is GeeksForGeeks";
Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type.
Note: Do not use cstring or string.h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.Pros:When dealing exclusively in C++ std:string is the best way to go because of better searching, replacement, and manipulation functions.Some of the useful std:string functions are discussed below.
CPP
// CPP program to illustrate // std::string functions#include <iostream>using namespace std;  int main(){    // string assignment    string s1 = "Hello";    string s2 = "World";      // return length of string    cout << s1.size() << endl; // 5    cout << s2.length() << endl; // 5      // concatenate string using + operator.    s1 = s1 + s2;    cout << s1 << endl; // HelloWorld      // append string    s1.append("Geeks");    cout << s1 << endl; // HelloWorldGeeks      string s3 = "HelloWorldGeeks";      // compare two strings    if (s1.compare(s3) == 0)        cout << "true" << endl;    else        cout << "false" << endl;      // substring of string s1    // substr(pos, length_of_substring)    string sub = s1.substr(0, 5);    cout << sub << endl; // Hello      // insert into string    // insert(pos, string)    s1.insert(10, "For");    cout << s1 << endl; // HelloWorldForGeeks      string target = "World";      // find a target string in s1    size_t pos = s1.find(target);    if (pos != std::string::npos) // npos=-1        cout << "Found at Position:" << pos << endl; // pos=5      // replace a portion of string s1    // replace(pos, length_of_portion, string_to_replace)    cout << s1.replace(5, 5, "Geeks") << endl; // HelloGeeksForGeeks      return 0;}
5
5
HelloWorld
HelloWorldGeeks
true
Hello
HelloWorldForGeeks
Found at Position:5
HelloGeeksForGeeks
Cases where you might prefer char* over std:string
When dealing with lower level access like talking to the OS, but usually, if you’re passing the string to theOS then std::string::c_str has it covered.Compatibility with old C code (although std::string’s c_str() method handles most of this).To conserve memory (std::string will likely have more overhead).
When dealing with lower level access like talking to the OS, but usually, if you’re passing the string to theOS then std::string::c_str has it covered.
Compatibility with old C code (although std::string’s c_str() method handles most of this).
To conserve memory (std::string will likely have more overhead).
3. Using char[]
Syntax:
char str[] = "This is GeeksForGeeks";
     or 
char str[size] = "This is GeeksForGeeks";
//  Here str is a array of characters denoting the string.

Pros:
We can modify the string at later stage in program.
We can modify the string at later stage in program.
CPP
// CPP program to illustrate char#include <iostream>using namespace std;  int main(){      char str[] = "Hello";    // or char str1[]={'H', 'e', 'l', 'l', 'o', '\0'};      // modify string to "Hollo"    str[1] = 'o';      cout << str << endl;      return 0;}
Hollo
Cons:
This is statically allocated sized array which consumes space in the stack.We need to take the large size of array if we want to concatenate or manipulate with other strings since the size of string is fixed. We can use C++ standard library cstring or string.h for that purpose.CPPCPP// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std;  int main(){    // take large size of array    char str[10] = "Hello";      cout << "Before Concatenation : " << str << endl; // Hello    strcat(str, " World");    cout << "After Concatenation : " << str; // Hello World      return 0;}Output:Before Concatenation : Hello
After Concatenation : Hello World

This is statically allocated sized array which consumes space in the stack.
We need to take the large size of array if we want to concatenate or manipulate with other strings since the size of string is fixed. We can use C++ standard library cstring or string.h for that purpose.CPPCPP// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std;  int main(){    // take large size of array    char str[10] = "Hello";      cout << "Before Concatenation : " << str << endl; // Hello    strcat(str, " World");    cout << "After Concatenation : " << str; // Hello World      return 0;}Output:Before Concatenation : Hello
After Concatenation : Hello World

CPP
// CPP program to illustrate char// concatenation using standard functions#include <iostream>#include <cstring>using namespace std;  int main(){    // take large size of array    char str[10] = "Hello";      cout << "Before Concatenation : " << str << endl; // Hello    strcat(str, " World");    cout << "After Concatenation : " << str; // Hello World      return 0;}
Before Concatenation : Hello
After Concatenation : Hello World

Here are couple of other useful functions of C++ standard library cstring.
CPP
#include <iostream>#include <cstring>using namespace std;  int main(){    char s1[10] = "Hello";      // return length of s1    cout << strlen(s1) << endl;      char s2[50];      // copies s1 into s2    strcpy(s2, s1);    cout << s2 << endl;      char s3[10] = "World";      // concatenates s3 into s2    strcat(s2, s3);    cout << s2 << endl;      char s4[50] = "HelloWorld";      // return 0 if s2 and s4 are equal.    if (strcmp(s2, s4) == 0)        cout << "true" << endl;    else        cout << "false" << endl;      char s5[30];      // copies first 5 chars of s2 into s1    strncpy(s5, s4, 5);    cout << s5 << endl;      char target[10] = "Hello";      // search for target string in s4    if (strstr(s4, target) != NULL)        cout << "true" << endl;    else        cout << "false" << endl;      return 0;}
5
Hello
HelloWorld
true
Hello
true
This article is contributed by Kshitiz Gupta. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SHSGM
simmytarika5
rajasachithanantham
cpp-string
cpp-strings-library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples