TutorialsCC Strings
Share:

C Strings

intermediate

Part of Program Flow in C

Theory

In C, strings are null-terminated character arrays. Unlike higher-level languages, C has no built-in string type — strings are simply arrays of char ending with the null character \0.

Char Arrays and Null Terminator

A string literal like "Hello" is stored as {'H', 'e', 'l', 'l', 'o', '\0'}. The null terminator \0 marks the end of the string. All string functions rely on this terminator to know where the string ends.

char str1[] = "Hello";           // Auto-sized: 6 bytes (includes \0)
char str2[20] = "Hello";         // Fixed size: 20 bytes
char str3[] = {'H', 'i', '\0'};  // Manual initialization

string.h Functions

The <string.h> header provides essential string manipulation functions:

  • strlen(s) — returns the length (excluding \0)
  • strcpy(dest, src) — copies src to dest
  • strcat(dest, src) — appends src to dest
  • strcmp(s1, s2) — compares strings (0 if equal, negative if s1 < s2, positive if s1 > s2)

String Input

Use fgets() for safe string input (it prevents buffer overflow). scanf("%s") reads until whitespace but is unsafe for long inputs.

Practical Examples

Example 1: String Basics and string.h Functions
c
Example 2: Safe String Input with fgets()
c

Exercises

String Palindrome Checker

medium

Write a C program that reads a string using fgets(), removes the newline, and checks whether the string is a palindrome (reads the same forward and backward). Print 'Palindrome' or 'Not a palindrome'.

Starter Code:

#include <stdio.h>\n#include <string.h>\n\nint main() {\n  char str[100];\n  // Your code here\n  return 0;\n}

Expected Output:

Enter a string: radar\nPalindrome

Mini Quiz

Mini Quiz