Character Classification and Conversion
The <ctype.h> header provides utilities for analyzing and modifying individual characters. These functions generally return non-zero values for true conditions and zero otherwise, adhering to standard integer logic rather than boolean types.
Classification Functions
These predicates evaluate the properties of a single character:
isalnum(char): Verifies if the input is alphanumeric (lettter or digit).isalpha(char): Checks whether the character is an alphabetic letter.isdigit(char): Determines if the character represents a numeric digit.isspace(char): Identifies whitespace characters such as spaces or newlines.islower(char)/isupper(char): Distinguishes between lowercase and uppercase letters.
Example
#include <stdio.h>
#include <ctype.h>
int main()
{
unsigned char testChar = 'Z';
if (isalpha(testChar))
{
printf("Character %c is alphabetic\n", testChar);
}
else
{
printf("Character %c is not alphabetic\n", testChar);
}
return 0;
}
Case Transformation
To alter the case of alphabetic characters, use tolower() for upper-to-lower conversion and toupper() for lower-to-upper. Non-alphabetic input are passed through unchanged.
#include <stdio.h>
#include <ctype.h>
int main()
{
char inputSymbol = '@';
char outputSymbol;
outputSymbol = tolower(inputSymbol);
printf("Input : %c \nOutput: %c\n", inputSymbol, outputSymbol);
return 0;
}
Standard String Manipulation
String operations reside in the <string.h> header. These functions operate on null-terminated character arrays (char *).
Length Calculation
The strlen() function counts characters excluding the trailing null terminator (\0).
#include <string.h>
char buffer[] = "Hello";
size_t length = strlen(buffer); // Result: 5
Custom Implementation
A manual implementation iterates until the null terminator is encountered.
size_t custom_strlen(const char* src)
{
size_t count = 0;
while (src[count] != '\0')
{
count++;
}
return count;
}
Copying and Concatenation
strcpy() copies the entire source string into the destination buffer. strcat() appends the source content to the end of the destination.
Copying
#include <string.h>
char target[20];
const char* original = "C Language";
// Copies source entirely; ensure target has enough space
strcpy(target, original);
Implementation Logic:
char* custom_strcpy(char* dest, const char* src)
{
char* start = dest;
while ((*dest++ = *src++) != '\0');
return start;
}
Concatenation
char strOne[30] = "Welcome ";
const char* strTwo = "User!";
strcat(strOne, strTwo);
Implementation Logic:
char* custom_strcat(char* dest, const char* src)
{
char* begin = dest;
// Move dest pointer to the null terminator
while (*dest != '\0') { dest++; }
// Append source characters including null
while ((*dest++ = *src++) != '\0');
return begin;
}
Comparison Operations
strcmp() compares two strings lexicographically. It returns an integer:
0: Strings are identical.- Negative: First string is smaller.
- Positive: First string is larger.
#include <string.h>
char s1[] = "Apple";
char s2[] = "Banana";
int diff = strcmp(s1, s2); // Returns negative value
Partial Comparison
strncmp() compares only up to a specified number of characters (n). Unlike standard comparison, it does not stop at a null character within the limit if one exists in the data, though usually, it respects the string termination if reached before n. If either string ends early, the comparision stops there.
#include <string.h>
char part1[] = "Computer";
char part2[] = "Compute";
if (strncmp(part1, part2, 7) == 0)
{
// Matches first 7 chars
}
Comparison Logic
int custom_strcmp(const char* s1, const char* s2)
{
while (*s1 && (*s1 == *s2))
{
s1++;
s2++;
}
return *(unsigned char*)s1 - *(unsigned char*)s2;
}
Searching and Splitting
Substring Search
strstr() locates the first occurrence of a substring within a string. It returns a pointer to the found location or NULL if not found.
char data[] = "Find the key here";
char* found = strstr(data, "key");
Logic Overview: This requires nested iteration. The outer loop advances through the main string, while the inner loop attempts to match the full pattern starting at that position.
char* custom_strstr(const char* haystack, const char* needle)
{
if (!*needle) return (char*)haystack;
while (*haystack)
{
const char* h = haystack;
const char* n = needle;
while (*h && *n && (*h == *n))
{
h++;
n++;
}
if (!*n) return (char*)haystack;
haystack++;
}
return NULL;
}
Tokenization
strtok() splits a string into tokens based on a delimiter set. Note that this function modifies the original string by inserting null terminators.
#include <string.h>
char text[] = "one,two,three";
char* token = strtok(text, ",");
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, ",");
}
System Error Reporting
The strerror() function maps error codes (typically from errno) to human-readable descriptions. This is essential for debugging failures, such as file I/O errors.
#include <stdio.h>
#include <errno.h>
#include <string.h>
FILE* handle = fopen("missing_file.txt", "r");
if (!handle)
{
fprintf(stderr, "Operation failed: %s\n", strerror(errno));
}
Ensure <string.h>, <ctype.h>, and <errno.h> are included when utilizing these respective libraries.