LearnFrenzy
Sign in Take a free test

C Programming · Topic 6 of 23

Strings

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Strings · Study material

A string in C is an array of char that ends with the null character '\0'. C has no string type: every function in <string.h> simply walks memory until it meets that zero byte. That makes strings fast and flexible, and it is also why buffer overflows, missing terminators and string-literal crashes are among the most common C bugs. This page teaches strings the modern, safe way, then gives you 40 practice questions checked on a real compiler.

On this page

  • String literals vs char arrays, strlen vs sizeof
  • Reading input safely with fgets()
  • The <string.h> functions you will use every day
  • snprintf(), strtok(), UTF-8 and what C23 adds

What is a string in C?

char word[] = "Frenzy"; creates an array of 7 bytes: the 6 letters plus a terminating '\0' that the compiler adds. strlen() counts the characters before the terminator; sizeof measures the whole array.

char word[] = "Frenzy";

  1. F0
  2. r1
  3. e2
  4. n3
  5. z4
  6. y5
  7. \06
#include <stdio.h>
#include <string.h>

int main(void) {
    char word[] = "Frenzy";              /* 6 letters + '\0' = 7 bytes */
    printf("strlen = %zu, sizeof = %zu\n", strlen(word), sizeof word);

    word[0] = 'f';                        /* an array is writable */
    printf("%s, code of word[6] = %d\n", word, word[6]);
    return 0;
}

Output

strlen = 6, sizeof = 7
frenzy, code of word[6] = 0

String literal vs char array

DeclarationWhat you getCan you change it?
char a[] = "hi";your own 3-byte array, a copy of the literalYes
const char *p = "hi";a pointer to the literal, often in read-only memoryNo – changing it is undefined behaviour
char a[8] = "hi";8 bytes: h, i, then six '\0'Yes
char a[2] = "hi";legal in C, but no room for '\0' – not a stringYes, but never pass it to string functions

Declare pointers to literals as const char *; the compiler then stops you from writing through them.

Reading strings safely

gets() was removed from C in C11 because it cannot know the buffer size. scanf("%s", s) stops at the first space and also has no limit unless you write one (%15s). The safe, standard way to read a line is fgets(), which keeps the newline – remove it with strcspn().

#include <stdio.h>
#include <string.h>

int main(void) {
    char name[16];
    if (fgets(name, sizeof name, stdin) == NULL)   /* never reads more than 15 chars */
        return 1;
    name[strcspn(name, "\n")] = '\0';              /* drop the newline fgets keeps */
    printf("Hello, %s! (%zu characters)\n", name, strlen(name));
    return 0;
}

Input

Asha Rao

Output

Hello, Asha Rao! (8 characters)

Everyday string.h functions

FunctionDoesWatch out
strlen(s)length before '\0' (size_t)O(n): do not call it in every loop test
strcpy(d, s) / strcat(d, s)copy / appendno size check – d must be big enough
strncpy(d, s, n)copy at most n charsno '\0' when s has n or more chars
strcmp(a, b)< 0, 0 or > 0not necessarily −1 or 1; never compare strings with ==
strchr(s, c) / strstr(s, t)find a char / a substringreturn NULL when not found
strcspn(s, set)length of the prefix with no char from setperfect for trimming '\n'
#include <stdio.h>
#include <string.h>

int main(void) {
    char a[20] = "learn";
    strcat(a, "frenzy");                              /* a has room for 19 chars + '\0' */
    printf("%s %zu\n", a, strlen(a));

    printf("%d %d %d\n", strcmp("apple", "banana") < 0,
           strcmp("abc", "abc") == 0, strcmp("b", "a") > 0);

    char *f = strchr(a, 'f');                         /* first 'f', or NULL */
    printf("%s (at index %td)\n", f, f - a);
    return 0;
}

Output

learnfrenzy 11
1 1 1
frenzy (at index 5)

Building strings with snprintf()

snprintf(buf, size, ...) never writes more than size bytes and always ends the result with '\0'. Its return value is the length the full result would have had, so you can detect truncation.

#include <stdio.h>

int main(void) {
    char buf[12];
    const char *kinds[] = {"ORDER", "INVOICE"};
    int ids[] = {42, 12345};

    for (int i = 0; i < 2; i++) {
        int need = snprintf(buf, sizeof buf, "%s-%04d", kinds[i], ids[i]);
        printf("%-12s needed %2d chars, truncated: %s\n", buf, need,
               need >= (int) sizeof buf ? "yes" : "no");
    }
    return 0;
}

Output

ORDER-0042   needed 10 chars, truncated: no
INVOICE-123  needed 13 chars, truncated: yes

Splitting with strtok()

strtok() writes '\0' into your string and remembers its position between calls, so the string must be writable, and two splits cannot run at the same time. Empty fields are skipped.

#include <stdio.h>
#include <string.h>

int main(void) {
    char line[] = "C,Java,,Python";          /* must be writable: strtok changes it */
    for (char *t = strtok(line, ","); t != NULL; t = strtok(NULL, ","))
        printf("[%s]\n", t);
    return 0;
}

Output

[C]
[Java]
[Python]

Characters, UTF-8 and C23

The <ctype.h> functions (isalpha, toupper …) expect a value that fits in unsigned char; pass (unsigned char) c, because a plain char can be negative. In UTF-8 text a letter such as é takes 2 bytes, so strlen() counts bytes, not characters. C23 makes strdup() and strndup() part of standard C and adds memccpy() for fast bounded copying.

Common string mistakes

  • No room for '\0': "Hello" needs 6 bytes, not 5.
  • Comparing with ==: it compares addresses; use strcmp().
  • Writing to a literal: char *s = "hi"; s[0] = 'H'; may crash.
  • Overflowing with strcpy/strcat: check sizes or use snprintf().
  • Forgetting the terminator after building a string by hand.

Key points to remember

  • A C string is a char array that ends with '\0'; size = length + 1.
  • strlen counts characters, sizeof counts bytes of the array.
  • Read lines with fgets(), build text with snprintf(), parse numbers with strtol().
  • String literals are read-only: point to them with const char *.
  • Cast to unsigned char before calling ctype functions.

Frequently asked questions

Why does C need '\0' at the end of a string?

Because a C string carries no length. Every function finds the end by looking for the zero byte.

What is the difference between strlen() and sizeof?

strlen() runs at run time and counts characters before '\0'. sizeof is the size of the array (or of the pointer, if you only have a pointer).

Is strcpy() unsafe?

It is safe only when you know the destination is large enough. When the length is not under your control, use snprintf() or check strlen() first.

Where can I learn strings step by step?

Read Strings in C, String Functions in C and String Programs for Practice, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links