CodeBlanks Logo Icon CodeBlanks

Summary - Strings

Combine strlen, strcpy and strcmp to write a name search app.

Summary: Strings

In this group you saw how strings work in C. Strings are char arrays terminated by the null character '\0'. String literals "..." add the null automatically.

Functions from <string.h>:

  • strlen: letter count
  • strcpy: copy to destination
  • strcat: append to destination
  • strcmp: compare (0 = equal)

Now let's combine everything in one task.

Practice Print the string length

Define a char array with the "Welcome" literal. Find the letter count with strlen and print with printf %zu. Output should be 7.

Starter code

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    /* define char array with "Welcome" */
    /* strlen for length and printf %zu to print */
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char s[] = "Welcome";
    printf("%zu\n", strlen(s));
    return 0;
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which function tests whether two strings are equal?

  • strcmp Correct answer
  • strcpy
  • strlen
  • strcat

Explanation: strcmp returns 0 when the strings are equal.

2 strcpy parameter order

Question
strcpy(____, src);  /* dst is destination, src is source */
Answer
strcpy(dst, src);  /* dst is destination, src is source */

Explanation: First parameter is destination (dst), second is source (src).

3 Function purposes

Term Meaning
strlen letter count
strcpy copy
strcat append
strcmp compare

All lessons in Beginner