Skip to content

Beginner · Strings in C · topic 17 of 60 · 30 min

The <string.h> functions

Explanation

<string.h> provides strlen (length without the \0), strcpy and strcat (copy and append, with no size checks), strncpy and strncat (with limits, but traps), strcmp (compare; 0 means equal), strchr and strstr (search), and memcpy and memset for raw bytes. snprintf(buf, sizeof buf, …) is the safest general way to build strings.

Length and comparison

c
#include <string.h>

size_t n = strlen("Mumbai");          /* 6 */
int r = strcmp("apple", "banana");    /* negative: "apple" comes first */
int s = strcmp("chai", "chai");       /* 0: equal */
int t = strcmp("Zebra", "apple");     /* negative: 'Z' (90) < 'a' (97) in ASCII */
if (strcmp(input, "yes") == 0) { … }  /* the correct way to test equality */
Careful: if (strcmp(a, b)) means "if they are DIFFERENT", because strcmp returns 0 for equal strings. Always write strcmp(a, b) == 0 for equality. And strcmp is case-sensitive; use strcasecmp (POSIX, not standard C) or compare lower-cased copies to ignore case.

Copying and appending

c
char dest[20];
strcpy(dest, "Hello");            /* copies including '\0'; NO size check */
strcat(dest, ", Pune");           /* appends; NO size check */
/* if the result does not fit in 20 bytes: buffer overflow (undefined behaviour) */

char safe[10];
snprintf(safe, sizeof safe, "%s, %s", "Hello", "Pune");   /* writes at most 9 chars + '\0' */
/* safe = "Hello, Pu" (truncated, but no overflow) */

The strncpy trap

c
char code[4];
strncpy(code, "PUNE", sizeof code);   /* copies 'P','U','N','E': NO room left, so NO '\0' added! */
code[sizeof code - 1] = '\0';         /* you must terminate it yourself → "PUN" */
strncpy also pads with zeros when the source is short. It was designed for fixed-width records, not as a "safe strcpy".

strncat(dest, src, n) appends at most n characters AND always adds \0, but n is the space REMAINING, not the total size: strncat(dest, src, sizeof dest - strlen(dest) - 1).

Searching

c
const char *email = "asha@bank.in";
char *at = strchr(email, '@');            /* pointer to the '@', or NULL if absent */
if (at) printf("Domain: %s\n", at + 1);   /* Domain: bank.in */
char *p = strstr("order-2026-OD55", "OD"); /* pointer to the first "OD" or NULL */

Raw memory: memcpy, memset, memcmp

c
int a[5] = {1, 2, 3, 4, 5}, b[5];
memcpy(b, a, sizeof a);          /* copy 20 bytes (non-overlapping regions only; use memmove if they overlap) */
memset(b, 0, sizeof b);          /* set every byte to 0 */
int same = memcmp(a, b, sizeof a) == 0;

Writing your own strlen

c
size_t my_strlen(const char *s) {
    size_t n = 0;
    while (s[n] != '\0') n++;     /* walk until the terminator */
    return n;
}
This is exactly why strlen is O(n): it must count every character each time it is called.
Think of it like this: strcpy is like pouring a jug of milk into a glass without looking: if the jug holds more than the glass, milk spills over the table (into neighbouring memory). snprintf is like pouring while watching the glass: it stops just before the brim and always leaves room for the lid (\0).
Tip: Calling strlen in a loop condition (for (i = 0; i < strlen(s); i++)) recounts the string every iteration, turning an O(n) loop into O(n²). Store the length in a variable first.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

The <string.h> functions · 1/6

string.h

In this lesson you will use the string functions from string dot h.

Prefer a video by a teacher? Find free videos on “c string.h functions strcpy strcmp strcat snprintf tutorial” on YouTube ↗

In real life: Building an SMS from parts

A bank's alert service builds SMS text from the account's last four digits, the amount and the date, into a fixed 160-byte buffer. snprintf guarantees the message can never overflow the buffer, whatever the data.

c
char sms[161];
const char *last4 = "4321";
double amount = 1250.0;
snprintf(sms, sizeof sms, "Rs %.2f debited from A/c XX%s on %s. Not you? Call 1800-XXX-XXXX",
         amount, last4, "19-10-26");
printf("%s (%zu chars)\n", sms, strlen(sms));

Practice (0/3 done)

Task 1 · Question

What does this print? char a[] = "Chai", b[] = "chai"; printf("%d\n", strcmp(a, b) == 0);

Task 2 · Question

char buf[8]; strcpy(buf, "Bengaluru"); What happens?

Task 3 · Practice

Write size_t my_strlen(const char *s), int my_strcmp(const char *a, const char *b) (returning <0, 0 or >0 like strcmp) and a function that builds "Name: <name>, City: <city>" into a caller-supplied buffer with snprintf, returning 0 on success and -1 if the text was truncated (snprintf returns the length it WANTED to write).

Quick quiz

Question 1

1.strcmp("abc", "abd") returns…

Question 2

2.Which function always respects the buffer size and terminates the result?

Question 3

3.strchr("asha@bank.in", '@') returns…

Question 4

4.When source and destination memory overlap, use…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

strcmp("abc", "abd") returns…

Answer: A negative number

'c' < 'd'.

Which function always respects the buffer size and terminates the result?

Answer: snprintf

snprintf writes at most size - 1 chars plus \0.

strchr("asha@bank.in", '@') returns…

Answer: A pointer to the @ character

It returns a pointer, or NULL if not found.

When source and destination memory overlap, use…

Answer: memmove

memcpy with overlapping regions is undefined behaviour.

What does atoi("abc") return?Related

Answer: 0, indistinguishable from the input "0"

That is why strtol is preferred.

From Reading strings safely

int a[] = {4, 5, 6, 7}; What is sizeof a / sizeof a[0]?Related

Answer: 4

Total bytes divided by bytes per element.

From Arrays

What does snprintf(NULL, 0, "%d", 12345) return?Related

Answer: 5

The number of characters the text would need (without the terminator).

From Dynamic strings and 2D arrays

How many bytes does "UPI" occupy as a string literal?Related

Answer: 4

3 letters + the terminator.

From Strings are char arrays

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Strings in C” before its exam: Reading strings safely, Characters and <ctype.h>, Buffer overflows and safe string handling.
  2. Module 4 exam: Strings in C · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Pointers. 60 topics left in the course before the final exam.

← Previous: Strings are char arrays