What is the difference between a character array and string?
-
1Please state your question as a question.Daniel A. White– Daniel A. White2009-11-05 13:19:26 +00:00Commented Nov 5, 2009 at 13:19
-
4In which language and how many marks will the answer earn you?Lazarus– Lazarus2009-11-05 13:19:35 +00:00Commented Nov 5, 2009 at 13:19
-
Java smells likely for this one.Josh Lee– Josh Lee2009-11-05 13:21:21 +00:00Commented Nov 5, 2009 at 13:21
5 Answers
Well, a string is a class which encapsulates behavior suitable for strings, such as Substring, Trim etc. The actual data is stored internally as a character array (at least in Java and C#), so there is a close connection between them, but the class itself represents more than just the characters.
There's more to it, in fact, such as internalization, but that's the gist of it.
Comments
A String is a character array with convenience methods to manipulate the array (searching, substring, pattern matching). In many languages (Java, for example), the String is immutable (just like the number 5: You can assign it to a variable but you can't change the value of the number, i.e. 5 = 1; will not work) while the character array is just like any other array where you can change the content (for example, you can replace the first character of the array with something else with array[0] = ... which is not possible with a string).
This allows the language compiler to make some optimizations when working with strings. For example, when you ask for a substring, then you get a reference for the character array backing the original string and the new object has some offsets to give you the illusion that it's a new string.
1 Comment
1.There is no such data type as a string in C, which can be replaced by an array of char 2.The string must be an array of chars, but an array of chars is not necessarily a string 3.A char array ending in a number 0 (equivalent to the character '0') is a string, but if the char array does not end with the number 0, then it is not a string, just an array of ordinary characters, so the string is a special kind of char array.