Which is preferred std::string or char str[] or char *str | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Which is preferred std::string or char str[] or char *str

From C++ tutorial got 3 different way to represent a string. Can someone explain what is the difference between below string variables and use cases. std:string = "sololearn; char str[] = "sololearn"; char * str = "sololearn";

14th Oct 2021, 6:40 AM
Sushil 🛡️
Sushil 🛡️ - avatar
2 Answers
+ 4
cpp uses a string class so that one should be easiest to work with.
14th Oct 2021, 6:55 AM
Slick
Slick - avatar
+ 3
std::string is a class that allows for variable length strings, you can add characters to it or remove characters, as well as alot of other useful manipulation functions. Probably the most used. The other types are mostly used in C. char[] is a build-in data type that is a fixed length string on compile time, while you cannot change the size of the string, you can change the characters. char* is used for dynamic string allocation at run time, something that std::string uses internally. But you have to reallocate every time you add or remove characters. Something std::string does for you. char* str = "..." is the incorrect data type to use without new or malloc. const char* = "..." is used for constant and fixed length strings. These are put directly into your executable and you cannot change, add or remove the characters.
14th Oct 2021, 8:11 AM
Dennis
Dennis - avatar