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?
相关问题
- How to introduce AOP into productive software deve
- What is the difference between Dataflow programmin
- What is the opposite of OOP? [closed]
- What is the difference between procedural programm
- In which layer should I join 2 entities together?
相关文章
- How to introduce AOP into productive software deve
- What is the difference between Dataflow programmin
- What is the opposite of OOP? [closed]
- What is the difference between procedural programm
- C ++技术:类型擦除与纯多态性(C++ Techniques: Type-Erasure vs.
- In which layer should I join 2 entities together?
- 混入与性状混入与性状(Mixins vs. Traits)
- Practical uses of OOP
In C, a string is an array of characters terminated by a null character(\0) but
In C++, a string is a class and we use its object and there is no null character at the end but an array of characters contains null character at the end.
Also, we can use operators with the string object in C++.
I used to teach programming, and this is how I used to explain this particular issue.
First, focus on what both things have in common: both a char array and a string consist of a sequence of characters. Being a sequence implies that the characters are ordered and that they can be enumerated, for example.
Now focus on what each of the two things add, in their particular different ways, to this common ground.
A char array adds what any array is known to add: indexing and random access to individual items.
A string, on the other hand, adds the fact that the sequence of chars is seen as a whole thing with its own properties. In some implementations, achieving this means altering the way the chars are stored (adding a terminating null in C strings, for example).
This approach (look at the commonalities, then at how things diverge from them) has proven useful in a variety of situations.
Hope this helps.
The answer to some extent depends on what language your talking about. In the .Net/C# world strings are immutable objects, whereas a char array you can add/change values easily in the array. Strings can be treated as char arrays in a read-only fashion, as you can iterate over the characters in a string.
In the abstract I think the biggest difference is in how you want to work with them. Are you wanting to work with a chunk of text, say to show a message to an end user, or are you looking at a sequence of characters, doing some processing on the list? It's all rather subjective at a certain level.
A C-style string is internally represented by array of character with the '\0' at end, which indiciates the end of string.
In C++, there's a string container class defined in string.h which provides some typical string operations to manipulate the string.