views:

400

answers:

3

What is the difference between a character array and string?

+4  A: 

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.

Tor Haugen
A: 

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.

Aaron Digulla
The statement that "you get a reference for the character array backing the original string and the new object has some offsets..." may or may not be true depending on what language you are using, and even sometimes which runtime and/or version of the language. For example, the original Visual Basic did share string data this way but VB.NET doesn't. Each approach is optimal in different situations, so there is no one "right" answer, though it does seem like most new language implementations today choose not to share string data as described.
Ray Burns
A: 

String is a class whose objects can be created and initialised by formaly calling the constructor or by direct assignment. 1) String s = new String("abc"); 2) String s = "sachin";

Whereas character array is the contigeous storage in memory were characters are stored sequentially.

Sachin Chourasiya