As mentioned in a previous post, strings in C are kind-of blah. Part of this has to do with the use of a string terminator, and the fact that they are not first-class objects. What about using length counts instead? How would this be achieved? One way would be to store the length count in a single byte at the start of the string, say index 0? This does have the effect of limiting the length of a string to 255 characters, but this rally shouldn’t be a problem. If you are storing larger strings, there is likely a better data structure, or you could simply use an array of characters Differentiating it in this way is similar to how Fortran deals with arrays. Too complicated? Unlikely, especially for the novice programmer, who no longer has to deal with the terminating string fiasco. Also strings could be indexed from 1..n without the loss of the precious “0-index”, which is used for storing the length of the string.
So what would a rejigged string look like? A simple string, with a maximum length of 255, might look like this (adopted from the keyword used by ALGOL 68):
This means that s to s would contain the characters in the string and s would contain the length of the string. A longer string might be achieved through using the moniker long. For example:
long string s;
This would create a string with 2000 characters. Making an array of strings might be accomplished by:
This would create an array of 40 strings, each 30 characters in length. Another annoying feature of C is that it provides functions for string to number, but not vice versa. This could be fixed by having a cast operator (string), which avoids having to use sprintf().
Of course, in an ideal world these strings would be even more efficient if they were coupled with the ability to use substrings s[i:j], overload the + operator for concatenation, == for equality and use !s to return the string length, but then, maybe I’m thinking of another language…