digitalmars.D - strings and char arrays
- llee (1/1) May 05 2008 With the release of dmd 2, char arrays have been replaced with strings. ...
- Robert Fraser (27/28) May 05 2008 arrays, and the strings that have replaced them are not terminated with
With the release of dmd 2, char arrays have been replaced with strings. Many of the standard functions within Phobos no longer accept character arrays, and the strings that have replaced them are not terminated with null characters - making them incompatable with c functions. Equally important strings are immutable, meaning that they can not be modified after they are defined, and old code that used the word string for variable names and references no longer work. Why have strings been introduced? Why are they being used to replaced character arrays when they suffer from these limitations and introduce these problems? And, how can we convert between char arrays, and strings?
May 05 2008
llee wrote:With the release of dmd 2, char arrays have been replaced with strings.Many of the standard functions within Phobos no longer accept characterarrays, and the strings that have replaced them are not terminated with null characters - making them incompatable with c functions. Equally important strings are immutable, meaning that they can not be modified after they are defined, and old code that used the word string for variable names and references no longer work. Why have strings been introduced? Why are they being used to replaced character arrays when they suffer from these limitations and introduce these problems? And, how can we convert between char arrays, and strings? strings _are_ character arrays, just immutable ones. D's char[]s and C's char*s were never compatible -- D's arrays keep a length in them, which takes up a little bit more memory but makes a surprising number of operations more efficient. In D2, the concept of invariantness was introduced, and the identifier "string" was aliased to mean invariant(char)[]. There have been numerous arguments about whether this is a good choice or not, start browsing this newsgroup if you're curious. The main arguments are that invariant is more efficient and people have an easier time thinking of strings as immutable entities. To convert... char* -> char[] -- fromStringz(x) char[] -> char* -- toStringz(x) invariant(char)[] -> char[] (copy made) -- x.dup invariant(char)[] -> char[] (no copy) -- cast(char[]) x char[] -> invariant(char[]) (copy made) -- x.idup char[] -> invariant(char)[] (no copy) -- cast(invariant) x Remember that string and invariant(char)[] are interchangeable
May 05 2008