Skip to main content
Logo image

Dive Into Systems: Exercises

Section 2.6 Strings and the String Library

Exercise 2.6.1. Strings and Characters.

    Given the following variable declarations, which of the following lines are syntactically valid ways that character and string types can interact?
    char c, s[20];
  • c = s[0];
  • s = c;
  • c = "A";
  • s = 'A';
  • c = 'A';
  • s[0] = c;
Hint 1.
There is no string type; instead, strings are implemented as arrays of chars. You can’t simply interchange strings and chars in a line of code, as they are fundamentally different under the hood.
Hint 2.
Character literals use single quotes, like: ’A’. String literals use double quotes, like: "A".

Exercise 2.6.2. The strlen Function.

What will strlen("Hello!") return?
Hint.
The null character at the end of a string takes up a byte of memory, but it does not count for the string length.

Exercise 2.6.3. Storing Strings.

Suppose you want to store this string: "Hello!" How many bytes do you have to pass to malloc to allocate enough memory to store it?
Hint 1.
Each character takes up one byte of memory.
Hint 2.
Don’t forget the null character at the end of the string takes up one byte of memory!

Exercise 2.6.4. Storing Strings and strcat.

Suppose you have the strings "Hello" and "World" and you strcat them together. How many bytes are needed to store the result?
Hint.
Recall that strcat concatenates two strings together.

Exercise 2.6.5. Code Safety.

    Which of these functions is a safer alternative to strcpy?
  • strncpy
  • Correct
  • strtok
  • Incorrect
  • ststr
  • Incorrect
  • sprintf
  • Incorrect
Hint.
There is a version of strcpy that adds safety by passing in an N value that is the maximum size to copy, which is usually the size of the destination string.

Exercise 2.6.6. Dynamic String Concatenation.

Put these lines of code in order to successfully create the string "Hello World" (held in result) after the code finishes.
Hint.
Think about whether you should do a string copy or a string concatenation first.

Exercise 2.6.7. String Overflow and Undefined Behavior.

Hint.
There is not enough room in most of the arrays to copy any additional characters into them. This is a common mistake that new C programmers make.

Exercise 2.6.8. Built-in Character Functions.

Exercise 2.6.9. Uppercaseifying a String.

Write a function called uppercaseify that takes a string parameter and modifies the string’s letters to be all uppercase.
So a call to uppercaseify passing the string "yo ho ho!" would modify the string to be "YO HO HO!".
Answer.
Here is a sample solution:
void uppercaseify(char *str) {
    int i, len;

    if(str == NULL) {
        return; //error handling
    }

    len = strlen(str);
    for (i = 0; i < len; i++) {
        str[i] = toupper(str[i]);
    }
}