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

The enter key that the user presses after the name does not terminate the input. readf() continues to wait for more characters to add to the string:

What is your name? Mert
← The input is not terminated although enter has been pressed
 ← (Let's assume that enter is pressed a second time here) 

One way of terminating the standard input stream in a terminal is pressing Ctrl- D under Unix-based systems and Ctrl-Z under Windows systems. If the user eventually terminates the input that way, we see that the new-line characters have been read as parts of the string as well:

Hello Mert
← new-line character after the name
! ← (one more before the exclamation mark)

The exclamation mark appears after those characters instead of being printed right after the name.
readln() is more suitable when reading strings. Short for “read line,” readln() reads until the end of the line. It is used differently because the " %s" format string and the & operator are not needed:

Get hands-on with 1400+ tech skills courses.