string or char array - any diff.?

Is there any difference?

string greeting = "Hello";

char greeting[] = "Hello";

Introduction to strings

Character Sequences

Get C string equivalent
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.

char greeting[] = "Hello"; is C. string greeting = "Hello"; is C++.

Why would you ever use one over the other? Well there really isn't must use for the C version. Both will store characters, you can access each character individually with the [] operator, but that's where the C version ends.

In addition to the above activities, strings can be resized, compared, searched, swapped. You can erase intermediate characters, swap strings, and you have protections (exceptions) when trying to access characters which are out of bounds.

All of this is done by using member functions that belong to the class so you don't need to include additional headers. It's all documented here:

With the C strings (char[]), you have the benefit of not including <string>, but to perform any operations on the string, you need to include <cstring> and you can pretty much only compare strings (with strcmp() not with ==) and assign strings (with strcpy(), not with =). There are a few other functions in there, but not as useful as the std::string class, and no dynamic sizing or boundary protections.
Last edited on

It looks like C++ string has a lot of advantage over C.

I'll use that. Thanks.
Topic archived. No new replies allowed.