C chapters

Chapter 11 of 17

Strings

Try this in our C Compiler →

Text is everywhere

Almost every program reads, manipulates and prints text. C represents text as a string — a sequence of characters. Strings are immutable in many languages, meaning every "change" actually produces a brand new string and leaves the original alone.

#include <string.h>
char name[] = "PlayLearn";
printf("%lu\n", strlen(name));
char greet[64];
sprintf(greet, "Hello, %s!", name);

Common string operations

Concatenation joins two strings together. Slicing extracts a portion. Searching finds whether a substring exists. Splitting breaks a string into pieces around a separator. Replacing swaps one substring for another. These five operations cover the vast majority of real-world text work.

Formatting and templates

When you need to drop variables into a string, prefer the language's built-in template syntax over manual concatenation. It is shorter, harder to get wrong, and produces clearer code that other developers can scan in a glance.

Details for c

scanf reports successful conversions; fgets reads a bounded line and may retain its newline. Mixing them leaves separators to handle. Check conversion counts and buffer capacity before using input. Compile every required .c file.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on