C Strings
intermediatePart 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 initializationstring.h Functions
The <string.h> header provides essential string manipulation functions:
strlen(s)— returns the length (excluding\0)strcpy(dest, src)— copiessrctodeststrcat(dest, src)— appendssrctodeststrcmp(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
Exercises
String Palindrome Checker
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