What is the difference between the string and character array?
How can each element of the string b开发者_高级运维e accessed in C++?
string
manages its own memory; this is not so with an array of char
except as a local variable.
In both cases you can access individual elements using []
(but in the case of string this is actually operator[]
).
string
has a lot of built-in functions that you don't easily get in a C++-friendly way with C-Strings.
In C, they are the same, a string is a char array and you have a lot of standard methods to handle them like sprintf, strcat, strcpy, strdup, strchr, strstr...
In C++, you can also use the STL string class that will provide a object oriented string that you can manipulate in an easier way. The advantage is that the code is easier to read and you don't need to allocate/deallocate memory for the strings by yourself.
精彩评论