What is the difference between a Char Array and a

2019-01-24 02:01发布

Spending my time on high level languages it suddenly occurred to me that I did not know the difference between a Char Array and a String. I think they are the same thing but not sure. Is there a difference? Is it just a Char Array with some abstraction?

标签: paradigms
10条回答
forever°为你锁心
2楼-- · 2019-01-24 02:27

In C these are almost the same, though a string will have an additional null character at the end.

In other languages (Java, C# etc), a string is an object, whereas a character array is an array of ... chars (which are primitive data types).

Normally, strings are implemented with character arrays.

查看更多
男人必须洒脱
3楼-- · 2019-01-24 02:28

a character array is simply an array of characters

a string is data structure that uses an array of characters

some string representations use a null-terminator (like C), others use a length prefix

查看更多
Bombasti
4楼-- · 2019-01-24 02:31

A string is the character array terminated by null character ‘\0’

查看更多
Lonely孤独者°
5楼-- · 2019-01-24 02:33

It depends on the language. In C-ish languages, they are pretty much synonomous. You could claim the difference is that "strings" have an implicit terminating nul, but that would be splitting hairs.

Fortran is the other extreme. There character arrays and character strings are entirely different types, with different operations available for them.

查看更多
Emotional °昔
6楼-- · 2019-01-24 02:34

String is a class in java. So it has attributes e.g. length. So when you ask for the size of string it simply returns that instead of computing the value each time. It also other methods e.g. indexOf, substring, etc to make life easy so you don't have to do that yourself.

查看更多
该账号已被封号
7楼-- · 2019-01-24 02:37

A String is an abstraction, but of a sequence of characters. It says nothing of implementation. If you wanted to create a String implementation based on a linked list of characters there's nothing stopping you.

In a language such as C, there is very little difference - just that a c string is a null-terminated series of characters at sequential addresses, that is generally accessed through a pointer.

In an OOP language, a String will be an object of some String class. This will probably hold the data in a character array internally, but you don't need to know that. A character array can only be a simple array, but a String class can provide many operations (substrings, regex, etc) on strings if the implementer decides to.

查看更多
登录 后发表回答