← The C Language Lesson 22 of 77 · 10 XP

Strings

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

C has no separate "string" type. A string is an array of char that ends with a null character '\0':

char name[] = "Kai";     // in memory: 'K' 'a' 'i' '\0' — 4 bytes!
char buf[32];            // room for a string of up to 31 characters + '\0'

It's by the '\0' that functions find out where a string ends. Forget it, and the function will go on reading memory beyond it.

Functions from <string.h>:

strlen(s)          // length without the '\0'
strcpy(dst, src)   // copy (dst must have room!)
strcat(dst, src)   // append to the end
strcmp(a, b)       // compare: 0 — equal, <0 — a is less, >0 — greater

Strings can't be compared with ==: that compares addresses, not contents. Use strcmp.

Reading: scanf("%31s", buf) reads one word of no more than 31 characters. The number in the template protects against a buffer overflow. A whole line with spaces is read by fgets(buf, sizeof buf, stdin).

About non-English letters: in UTF-8 an accented or non-Latin letter takes 2 or more bytes, so strlen("café") = 5. In tasks about characters we use plain Latin letters.

Task. Read a word (Latin letters, up to 100 characters) and print it backwards. Do it yourself, without a library function for reversing.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.