Search⌘ K
AI Features

Strings

Explore how strings work in D as arrays of characters with three distinct types. Understand reading strings from input using readln and stripping unwanted characters. Learn to parse input with formattedRead and compare strings case-insensitively with icmp, while managing immutability of string types.

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? ");
readf(" %s", &name); 
writeln("Hello ", name, "!");

The ...