πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English
Advertisement

Lesson 12: 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 first time is normal
Strings combine pointers and arrays; if either concept is shaky, strings feel messy.
How to retry
  1. Nail arrays first (char s[10] is just an array)
  2. Learn pointers, then return
  3. Remember the trailing \0 (NUL terminator) β€” it marks the end
  4. Recall that char is really an integer (ASCII code)
  5. For unfamiliar functions (e.g., strlen), learn how to use them first, internals later
πŸ’‘ Tip: "Hello" is really a 6-byte array {'H','e','l','l','o','\0'}. "String = array + terminator" is enough to start.

What is a string?

C has no string type. Instead, strings are represented as arrays of char.
Key point: Every C string ends with a null character '\0', which marks where the string ends.
char name[20] = "Claude"; // up to 19 chars + '\0'
printf("%s\n", name); // -> Claude
%s is the string format specifier. Pass just the array name (the address of the first element).

The truth about char β€” characters are numbers (ASCII)

Before going deeper you need this key fact:
A char is really a 1-byte (8-bit) integer. The letter 'A' you see on screen is nothing more than the number 65 interpreted as a character.
Core idea: char c = 'A'; and char c = 65; are exactly the same.
printf("%c", 65) β†’ A / printf("%d", 'A') β†’ 65

ASCII cheat sheet (main ranges)

CharDecimalMeaning
'\0'0NUL (string terminator)
'\n'10newline
' '32space
'0'–'9'48–57digits ('0' = 48)
'A'–'Z'65–90uppercase letters
'a'–'z'97–122lowercase letters
'a' - 'A' = 32 β€” the gap between lower and upper case drives several common tricks.

Example: characters and numbers interchange

#include <stdio.h>

int main(void) {
    char c = 'A';
    printf("c = %c\n", c);     // β†’ A  (as a character)
    printf("c = %d\n", c);     // β†’ 65 (as a number)

    // arithmetic on characters works
    printf("%c\n", c + 1);    // β†’ B  (65+1=66)
    printf("%c\n", 'Z' - 3);  // β†’ W

    // storing 65 in a char is the same as 'A'
    char d = 65;
    printf("%c\n", d);        // β†’ A
    return 0;
}

Classic idioms

β‘  Upper to lower case
char c = 'A';
char lower = c + ('a' - 'A');   // 'A' + 32 = 'a'
// or: char lower = c + 32;
β‘‘ Convert a digit character to its integer value
char ch = '7';            // this is 55 (ASCII for '7')
int n = ch - '0';        // 55 - 48 = 7
printf("%d\n", n);       // β†’ 7
β‘’ Character tests (uppercase / digit)
if (c >= 'A' && c <= 'Z') // uppercase?
if (c >= '0' && c <= '9') // digit?
// <ctype.h> also provides isupper(c), isdigit(c)

Why is char an integer in the first place?

Back in the 1960s ASCII (American Standard Code for Information Interchange) defined a mapping "letters/digits/symbols ↔ 7-bit numbers". C inherited this by treating characters as integers. This simple design is what makes character arithmetic so easy in C.
Caveat: non-ASCII characters don't fit in one char.
char c = 'あ'; is an error or warning. Non-ASCII characters need multiple bytes (3 bytes in UTF-8), so you store them in a char array or use wchar_t. Only ASCII (letters, digits, punctuation) is safe in a single char.

char array memory layout

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

String I/O

Use %s for string I/O. In 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 its address is passed automatically.
[!] Pitfalls of scanf("%s"): It splits on whitespace and does not 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 understand how it works, let's look at 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
}
You can see why the null character '\0' is so important — it's the marker that signals the end of the string.

string.h functions

The most important string functions available via #include <string.h>.
FunctionPurposeExampleNotes
strlen(s)String lengthstrlen("abc") -> 3Does not include '\0'
strcpy(dst, src)Copy stringstrcpy(s, "Hello")dst must be large enough
strncpy(dst, src, n)Copy up to n charsstrncpy(s, src, 10)Prevents buffer overflow
strcat(dst, src)Concatenatestrcat(s, " World")dst must fit the result
strcmp(s1, s2)Compare stringsstrcmp(a, b) == 00 = equal; +/- for order
strncmp(s1, s2, n)Compare first n charsstrncmp(s, "ab", 2)Good 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 (%lu chars)\n", greeting, strlen(greeting));
    return 0;
}
Never compare strings with ==!
if (s1 == s2) compares addresses, not contents.
Always compare with strcmp(s1, s2) == 0.
Beware of buffer overflow:
strcpy and strcat do not check destination size.
Use a large enough array, or limit the copy with strncpy.

Try it yourself — strings

A program that prints a string and its length.
string.c
Output
Click "Run" to execute...
πŸ’‘ Try these ideas too
Advertisement

Related Lessons

Arrays & Strings
Lesson 11: 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 25: Pointer Basics
Understand C pointers through memory visualization.
← Previous lesson
Lesson 18: Arrays
Next lesson →
Lesson 20: Functions (Basics)

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 by a null character \0, which lets code determine the string's length.

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

5
6
7

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

Q3. Which function copies a string?

strcpy
strcmp
strlen

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

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

Recommended Books to Deepen Your Understanding

Combine this interactive site with books for more practice.

πŸ“˜
Painfully Learning C
by MMGames
A classic C book for beginners. Builds solid fundamentals with clear explanations.
View on Amazon
πŸ“—
New Clear C Language (Beginner)
by Bohyoh Shibata
Plenty of diagrams and exercises. Widely used as a university textbook.
View on Amazon
πŸ“™
The C Programming Language, 2nd Ed.
by Brian Kernighan & Dennis Ritchie
Known as K&R. The original C book. Ideal after completing the basics.
View on Amazon

* Links above are affiliate links. Purchases help support this site.