Chapter 9: Strings in C

A string in C is simply a collection of characters (letters, numbers, symbols) that ends with a special character called null terminator (\0).

In C, there is no built-in string type like in Python or Java. Instead, a string is just a character array (char[]) that ends with \0.

1. String Declaration and Initialization

Declaration:

C

Initialization ways:

Way 1: Using double quotes (most common)

C

Way 2: Character by character (with null terminator)

C

Way 3: Without size (only when initializing)

C

Important Rule:

  • Always leave one extra space for the \0 (null terminator)
  • If you forget \0, many string functions will not work properly (they keep reading memory until they find \0)

2. String Input and Output

Output (Printing Strings): Use %s format specifier in printf()

C

Input (Reading Strings): Use scanf() or gets() or fgets() (recommended)

Using scanf() – reads until space

C

Problem: scanf(“%s”) stops at space → can’t read full name like “Alex Smith”

Better way: fgets() – reads whole line including spaces

C

Note: fgets() includes the Enter key (\n) at the end – we can remove it if needed.

3. Important String Manipulation Functions

(You need to include <string.h> header)

Function Purpose Example
strlen() Returns length of string (without \0) strlen(“Hello”) → 5
strcpy() Copies one string to another strcpy(dest, src)
strcat() Concatenates (joins) two strings strcat(dest, src)
strcmp() Compares two strings Returns 0 if equal, negative/positive if different
strchr() Finds first occurrence of character strchr(“Hello”, ‘l’) → pointer to first ‘l’
strstr() Finds substring strstr(“Hello World”, “World”)

Example Program – All Important Functions

C

Output:

text

4. More Real-Life String Examples

Example 1: Reverse a String

C

Example 2: Count Vowels in a String

C

Today’s Homework

  1. Write a program that takes a string from user and prints its length using strlen().
  2. Take two strings from user and join them using strcat() and print the result.
  3. Write a program to check if two strings are equal (using strcmp()).
  4. Create a program that takes a string and converts it to uppercase (use toupper() from <ctype.h>).
  5. Write a program to count how many times a particular character appears in a string.

You may also like...