Hi,
A
string in it's simplest form is an array of characters, also known as a C string. Arrays are tightly connected with pointers. A pointer is a variable which holds a memory address, which is just a number - on a 64 bit system it will be 8 bytes. Array indexes for a C string are simply an offset from the address of the beginning of the array: 0 offset is the first char, 1 the second etc.
Here's the thing: arrays
decay to their pointer address. Also a C style array of char is terminated with a null value '\0'. When the system is asked to print a string on the output with a function like printf (for C) or std::cout (for C++), the system prints the char at offset 0, followed by offset 1, until it reaches the null character, at which point it ends. Similar things happens when a string literal is used to initialise a char array, or some function is used to copy them etc.
Now std::string is a C++ class, which means an object created from the class can store data (the characters) and it has functions, algorithms and operators which can work with that data. For example, one can "add" strings to together with the + operator:
1 2 3 4 5 6 7 8
|
std::string h = "Hello ";
std::string w = "World!";
std::string Greeting = h + w ;
std::cout << Greeting << "\n" ;
// or
std::cout << h + w << "\n" ;
|
Note one can't do that with a C string, one must use a function to do that. Same for assigning one C string to another, can't just use the = operator, must use a function. But one can do that for std::string because it has overloads for various operators like =. std::string can also grow dynamically, where as a C string is a fixed sized array of char. So std::string is much more user friendly than a C string.
There are also algorithms, for example to find a character in a string. You can look at these in the reference section on this website.
The std::string class stores it's data dynamically on the heap, so there is no real need to use pointers or the
new
operator with it.
Good Luck !!
Edit :
In C++ you should avoid using arrays and pointers, use the STL (Standard Template Library) containers and their associated functions and algorithms. So try out std::vector and std::string instead of array of char and pointers. The reason for this is that STL things do their own memory management and have functionality built in to make things much easier and less error prone.