C Strings

Character arrays and string.h.

✍️ 2 exercises in this lesson

C has no string type: a string is an array of char ending with the null character '\0'.

  • char name[] = "Sara"; (5 bytes: S, a, r, a, \0)
  • <string.h> functions: strlen(), strcpy(), strcat(), strcmp()
  • Prefer the safer snprintf() and strncpy() to avoid buffer overflows.

Key Takeaways: C Strings

Mastering C Strings helps you write clean and reliable C code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C Strings Code Example

C
#include <stdio.h>
#include <string.h>

int main() {
    char first[20] = "Code";
    char second[] = "InTech";

    strcat(first, second);
    printf("%s (%zu chars)\n", first, strlen(first));
    printf("First letter: %c\n", first[0]);
    printf("Equal? %d\n", strcmp("abc", "abc") == 0);

    char msg[50];
    snprintf(msg, sizeof msg, "%s has %d lessons", "C", 20);
    printf("%s\n", msg);
    return 0;
}
Output
CodeInTech (10 chars)
First letter: C
Equal? 1
C has 20 lessons
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C Strings Practice Exercises

Check what you learned in “C Strings”.

/ 2 solved
Fill in the blank

Get the length of a string.

size_t len = (name);
✓ Correct! Not quite. Try again.
Multiple choice

How does a C string end?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services