Lesson 23: Strings

How to handle strings in C using char arrays, strlen, strcpy, and related functions.

📖 What to learn on this page
✅ Must-know essentials
  • A string is a char array ending with \0
  • printf("%s", s); prints it
  • char is really an integer (ASCII code)
  • strlen, strcpy, strcmp are in <string.h>
⭐ Read if you have time
  • Case conversion: c + ('a'-'A')
  • strcpy is unsafe — prefer snprintf
  • Non-ASCII chars don't fit in a single char
💪 Not getting it on the first try? That's normal.
Strings combine pointers and arrays, so if either concept is shaky they can feel messy.
How to approach it again
  1. Nail down arrays first — char s[10] is just an array
  2. Learn pointers, then come back
  3. Remember the trailing \0 (NUL terminator) — it marks the end
  4. Keep in mind that char is really an integer (an ASCII code)
  5. For unfamiliar functions like strlen, learn how to use them first, and worry about the internals later
💡 Tip: "Hello" is really a 6-byte array: {'H','e','l','l','o','\0'}. "String = array + terminator" is enough to get you started.

Represent strings with char arrays

In the previous lesson on char, you learned that one char variable stores one character value. An array of char places those values side by side, letting you represent multiple characters: a string.
'c'
[0]
'o'
[1]
'f'
[2]
'f'
[3]
'e'
[4]
'e'
[5]
'\0'
[6]
char values arranged in seven cells represent the string "coffee".
Key point: a C string ends with '\0', the null character. It marks the end; without it, printf cannot determine where the string stops.
char name[20] = "coffee";   // Reserve 20 char cells: up to 19 characters plus '\0'
printf("%s\n", name);       // → coffee
%s is the string format specifier. Pass the array name, which provides the address of its first element.

char array memory layout

Let's look at how the string "Hello" is laid out in memory.
char msg[6] = "Hello"; ← allocates 6 bytes (5 chars + '\0')
Watch the size! "Hello" is 5 characters, but you need 6 bytes — the 5 characters plus the trailing '\0'. Too small an array causes a buffer-overflow bug.

String I/O

Use %s for reading and writing strings. With scanf, note that you don't need &!
char name[20];
printf("Name? ");
scanf("%s", name); // no & needed
printf("Hello, %s\n", name);
Why no &? An array name like name decays to the address of its first element, so the address is already passed automatically.
[!] scanf("%s") gotchas: it stops at whitespace and doesn't check input length. Long input can overflow the array — in practice, fgets is safer.

Counting string length

strlen from the standard library is the easy way. To see how it works, let's build a home-made version.
// Count until '\0'
int myStrlen(char s[]){
  int i = 0;
  while(s[i] != '\0') i++;
  return i;
}

int main(void){
  char msg[] = "Hello";
  printf("%d\n", myStrlen(msg)); // -> 5
}
This is exactly why '\0' is so important — it's the marker that tells you where the string ends.

string.h functions

The most important string functions, available via #include <string.h>.
FunctionPurposeExampleNotes
strlen(s)String lengthstrlen("abc") → 3Doesn't include '\0'
strcpy(dst, src)Copy a stringstrcpy(s, "Hello")dst must be large enough
strncpy(dst, src, n)Copy up to n charsstrncpy(s, src, 9);
s[9] = '\0';
If src is too long, the terminating '\0' is not added — add it yourself
strcat(dst, src)Concatenatestrcat(s, " World")dst must fit the result
strcmp(s1, s2)Compare stringsstrcmp(a, b) == 00 = equal; +/- show order
strncmp(s1, s2, n)Compare first n charsstrncmp(s, "ab", 2)Handy for prefix checks
strchr(s, c)Find a characterstrchr(s, 'o')Returns NULL if not found
strstr(s, sub)Find a substringstrstr(s, "llo")Returns NULL if not found

strcpy and strcat example

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

int main(void) {
    char greeting[50];
    strcpy(greeting, "Hello");     // greeting = "Hello"
    strcat(greeting, ", World!"); // greeting = "Hello, World!"
    printf("%s (%zu chars)\n", greeting, strlen(greeting));
    return 0;
}
Never compare strings with ==!
if (s1 == s2) compares addresses, not contents.
Always use strcmp(s1, s2) == 0.
Watch out for buffer overflow:
strcpy and strcat don't check the destination size.
Use a large enough array. For a safe copy, snprintf(dst, sizeof dst, "%s", src); is handy (the result is always '\0'-terminated). If you use strncpy, add the trailing '\0' yourself as shown in the table above.

Try it yourself — strings

A little program that prints a string and its length.
string.c
Output
Press "Run" to execute...
💡 Try these ideas too

Related Lessons

Arrays & Strings
Lesson 20: Arrays
How to declare, initialize, and access C arrays, with memory diagrams.
Getting Started
Lesson 4: printf & scanf
How to use printf and scanf in C. A complete reference of format specifiers.
Advanced
Lesson 36: Pointer Basics
Understand C pointers through memory visualization.
Practice problems for this lessonStrings: 13 practice problemsWrite code in your browser and get it checked automatically. Hints and solutions included →
← Previous lesson
Lesson 22: Characters (char)
Next lesson →
Lesson 24: Quiz (Strings)

Review Quiz

Check your understanding of this lesson!

Q1. What is at the end of a C string?

Newline character \n
Null character \0
Space

C strings are always terminated with a null character \0, which is how code can tell where the string ends.

Q2. What array size is needed to store "Hello"?

5
6
7

"Hello" is 5 characters plus the null terminator, so 6 bytes total. You need char s[6] or larger.

Q3. Which function copies a string?

strcpy
strcmp
strlen

strcpy copies, strcmp compares, and strlen returns the length. Include <string.h> to use them.

Share this article
Share on X (Twitter) Share on Facebook Send on LINE Hatena