views:

83

answers:

2

what is the difference between the string and character array. how can each element of the string be accessed in C++.

A: 

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.

Benoit Thiery
Efficiency comment is likely to prove controversial if anybody can be bothered to read this question.
Steve Townsend
+1 on 'bothered to read'
KevinDTimm
Is it really worth a down vote? In my experience I saw an important difference in performance, but I agree for such a basic question, I could skip this. I remove it in my post.
Benoit Thiery
@Benoit - not to me, I did not -1 you.
Steve Townsend
Didn’t downvote but FYI, there is no performance difference on modern implementations of the STL. In fact, some string operations will be *faster* in C++, since querying the length of the string is an O(1) operation, whereas with C strings it’s an O(n) operation.
Konrad Rudolph
strings are not the same as char array. char array's are not restricted to ending with a specific character, or restricted in any way. \0\0\0\nI rule. is perfectly valid for a char array. A char array is not a string, it's just an array of dumb characters.
baash05
@baash05: right. We would usually use byte array and not char array in this case but it is true there is no restriction on the content. Good practice is to use unsigned char array when not storing strings except if you need the sign of course.
Benoit Thiery
+2  A: 

string manages its own memory, not so with an array of char except as a local variable.

In both cases you can access individual elements using [] - this is actually operator[].

string has a lot of builtin function that you don't easily get in a C++-friendly way with C-Strings.

Steve Townsend
-1 for the `[]` not being an operator
Let_Me_Be
@Let_Me_Be - fair enough, taking that out. Thanks.
Steve Townsend
@Steve: peer pressure is fickle. ;-) I actually preferred the previous formulation. Of course `[]` is an operator even for C strings but it’s not `operator []`.
Konrad Rudolph
@Konrad - yes, there is a qualitative difference between `[]` on string and arrays that is likely out of scope for this post. I will leave this here in comments, as it cannot then be directly downvoted.
Steve Townsend