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

Lesson 22: 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.

What is a string?

C has no dedicated string type. Strings are just arrays of char.
Key point: every C string ends with a null character '\0', which marks where the string stops.
char name[20] = "Claude"; // up to 19 chars + '\0'
printf("%s\n", name); // -> Claude
%s is the string format specifier. Just pass the array name β€” that's the address of its first element.

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

Before going any deeper, here's the 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 thing.
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 upper- and lowercase letters powers several common tricks.

Example: characters and numbers are interchangeable

#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

β‘  Uppercase to lowercase
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 from letters, digits, and symbols to 7-bit numbers. C inherited that mapping by treating characters as integers. That simple design is what makes character arithmetic so easy in C.
Caveat: non-ASCII characters don't fit in a single char.
char c = 'あ'; triggers an error or warning. Non-ASCII characters need multiple bytes (3 bytes in UTF-8), so they live in a char array or a wchar_t. Only ASCII (letters, digits, punctuation) is safe in a single char.

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, 10)Helps prevent buffer overflow
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 (%lu 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, or cap the copy with strncpy.

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 27: Pointer Basics
Understand C pointers through memory visualization.
← Previous lesson
Lesson 21: Quiz (Arrays)
Next lesson →
Lesson 23: 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