Strings in C: From Basics to Advanced
Last Updated on: 21st Jul 2025 00:32:57 AM
Strings in C are sequences of characters that add life to programs, enabling text manipulation for everything from user inputs to data processing. Unlike other data types, strings in C are handled as arrays of characters, terminated by a null character (\0). This tutorial covers strings, string handling functions (e.g., strlen, strcpy, strcat), and string input/output, progressing from beginner-friendly concepts to advanced applications. With unique, engaging examples using scanf and fgets for input, this guide is designed to captivate students on your website. Each example includes code, output, and a detailed explanation to ensure clarity and excitement. Let’s dive into the world of strings!
1. Introduction to Strings
A string in C is an array of characters ending with a null terminator (\0). It’s like a sentence in a book, where the null character marks the end. Strings are stored in char arrays and manipulated using standard library functions or custom logic.
Key Features:
-
Stored as char str[size] or char *str.
-
Null-terminated (\0) to indicate the end.
-
Used for text data, such as names, messages, or file content.
Why Use Strings?
-
Handle user input (e.g., names, passwords).
-
Enable text processing (e.g., searching, concatenation).
-
Support real-world applications like parsing or formatting.
2. String Syntax in C
Declaration:
char str[size]; // Fixed-size array
char str[] = "Hello"; // Initialized with string literal
Initialization:
char str[20] = "Hello, World!"; // Includes \0
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Explicit
Accessing Characters:
str[index]; // Access character at index (0 to length-1)
Input with scanf or fgets:
scanf("%s", str); // Reads until whitespace
fgets(str, size, stdin); // Reads entire line, including spaces
Output with printf:
printf("%s", str); // Prints entire string
3. String Handling Functions
The C standard library (<string.h>) provides functions for string manipulation:
-
strlen(str): Returns the length of str (excluding \0).
-
strcpy(dest, src): Copies src to dest, including \0.
-
strcat(dest, src): Appends src to dest, adding \0.
-
strcmp(str1, str2): Compares str1 and str2 (returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2).
-
strchr(str, ch): Finds the first occurrence of ch in str.
-
strstr(str, substr): Finds the first occurrence of substr in str.
4. String Input/Output
Strings can be input using scanf (for single words) or fgets (for lines with spaces) and output using printf.
Basic Example: Input and Output a Name
This program takes a user’s name and greets them.
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Reads until whitespace
printf("Hello, %s! Welcome to C programming.\n", name);
printf("Name length: %zu\n", strlen(name));
return 0;
}
Output (example user input: Alice):
Enter your name: Alice
Hello, Alice! Welcome to C programming.
Name length: 5
Explanation:
-
The name array stores up to 50 characters to prevent overflow.
-
scanf("%s", name) reads a word (no spaces) from the user.
-
printf outputs a greeting, and strlen calculates the name’s length (excluding \0).
5. String Handling Functions
Basic Example: String Concatenation and Comparison
This program takes two strings, concatenates them, and checks if they are equal.
#include <stdio.h>
#include <string.h>
int main() {
char str1[50], str2[50], result[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
strcpy(result, str1); // Copy str1 to result
strcat(result, " "); // Add space
strcat(result, str2); // Append str2
printf("\nConcatenated string: %s\n", result);
if (strcmp(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Output (example user input: Hello, World):
Enter first string: Hello
Enter second string: World
Concatenated string: Hello World
The strings are not equal.
Explanation:
-
scanf reads two strings into str1 and str2.
-
strcpy copies str1 to result, strcat appends a space and str2.
-
strcmp checks if str1 and str2 are equal (returns non-zero for "Hello" vs "World").
-
The result array is large enough (100) to hold both strings and a space.
6. String Input with Spaces
scanf stops at whitespace, so fgets is used for strings with spaces.
Example: Input and Reverse a Sentence
This program takes a sentence with spaces and reverses it.
#include <stdio.h>
#include <string.h>
int main() {
char sentence[100], reversed[100];
printf("Enter a sentence (up to 99 characters): ");
fgets(sentence, 100, stdin);
sentence[strcspn(sentence, "\n")] = '\0'; // Remove newline
int len = strlen(sentence);
for (int i = 0; i < len; i++) {
reversed[i] = sentence[len - 1 - i];
}
reversed[len] = '\0'; // Null-terminate
printf("Original: %s\n", sentence);
printf("Reversed: %s\n", reversed);
return 0;
}
Output (example user input: I love coding):
Enter a sentence (up to 99 characters): I love coding
Original: I love coding
Reversed: gnidoc evol I
Explanation:
-
fgets reads a line (including spaces) into sentence, up to 100 characters.
-
strcspn removes the newline from fgets.
-
A loop reverses the string by copying characters from sentence in reverse order to reversed.
-
The reversed string is null-terminated with \0.
7. Advanced Example: Word Frequency Counter
This program takes a sentence and counts the frequency of each word using string functions.
#include <stdio.h>
#include <string.h>
#define MAX_WORDS 50
#define MAX_LEN 20
int main() {
char sentence[100], words[MAX_WORDS][MAX_LEN];
int freq[MAX_WORDS] = {0}, wordCount = 0;
printf("Enter a sentence (up to 99 characters): ");
fgets(sentence, 100, stdin);
sentence[strcspn(sentence, "\n")] = '\0';
// Tokenize sentence
char *token = strtok(sentence, " ");
while (token != NULL && wordCount < MAX_WORDS) {
int found = 0;
for (int i = 0; i < wordCount; i++) {
if (strcmp(words[i], token) == 0) {
freq[i]++;
found = 1;
break;
}
}
if (!found) {
strcpy(words[wordCount], token);
freq[wordCount] = 1;
wordCount++;
}
token = strtok(NULL, " ");
}
printf("\nWord Frequencies:\n");
for (int i = 0; i < wordCount; i++) {
printf("%s: %d\n", words[i], freq[i]);
}
return 0;
}
Output (example user input: the quick fox the fox):
Enter a sentence (up to 99 characters): the quick fox the fox
Word Frequencies:
the: 2
quick: 1
fox: 2
Explanation:
-
fgets reads a sentence with spaces.
-
strtok splits the sentence into words using a space delimiter.
-
Each word is compared with existing words in words using strcmp.
-
If a word is new, it’s copied to words with strcpy, and its frequency is set to 1.
-
If a word exists, its frequency in freq is incremented.
-
The program prints each word and its count.
8. Why Strings Are Essential
Strings in C are crucial for:
-
Text Processing: Handle names, messages, or file data.
-
User Interaction: Process input for forms or commands.
-
Real-World Applications: Used in encryption, parsing, and UI.
Pro Tip: Experiment with these examples! Try extending the word frequency counter to ignore case,or create a string pattern matcher. Strings are your key to dynamic programming!
Happy coding