开发者

What is the difference between a character array and string?

What is the开发者_如何学Go difference between a character array and string?


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.


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.


A character array is basically something that can be used for storing multiple strings and it is possible to overwrite this array (i.e. it is mutable)

A string on the other hand needs a creation of an entirely new variable to overwrite the data.


String is a class whose objects can be created and initialised by formally calling the constructor or by direct assignment.

  1. String s = new String("abc");
  2. String s = "sachin";

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜