Strings

This lesson explains strings, its types and different functions that can be performed on strings.

Strings #

We have used strings in many of the programs that we have seen so far. Strings are a combination of the two features that we covered earlier in this chapter: characters and arrays. In the simplest definition, strings are nothing but arrays of characters. For example, char[] is a type of string.

This simple definition may be misleading. As we have seen in the characters: types and literals lesson, D has three separate character types. Arrays of these character types lead to three separate string types, some of which may have surprising outcomes in some string operations.

readln and strip, instead of readf #

There are surprises even when reading strings from the terminal. Being character arrays, strings can contain control characters like \n as well. When reading strings from the input, the control character that corresponds to the enter key that is pressed at the end of the input becomes a part of the string as well. Further, because there is no way to tell readf() how many characters to read, it continues to read until the end of the entire input. For these reasons, readf() does not work as intended when reading strings:

char[] name;
write("What is your name?
...
Access this course and 1400+ top-rated courses and projects.