c
examples
examples.cš§c
/**
* String Functions - Examples
*
* This file demonstrates standard library string functions.
*
* Compile: gcc examples.c -o examples
* Run: ./examples
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* ============================================================
* EXAMPLE 1: strlen() - String Length
* ============================================================ */
void example1_strlen(void) {
printf("=== EXAMPLE 1: strlen() ===\n\n");
char str1[] = "Hello";
char str2[] = "";
char str3[] = "Hello\0World";
printf("strlen() returns characters before null terminator:\n\n");
printf(" strlen(\"Hello\"): %zu\n", strlen(str1));
printf(" strlen(\"\"): %zu\n", strlen(str2));
printf(" strlen(\"Hello\\0World\"): %zu (stops at first \\0)\n", strlen(str3));
printf(" strlen(\"Hi There\"): %zu (spaces count)\n", strlen("Hi There"));
}
/* ============================================================
* EXAMPLE 2: strcpy() and strncpy()
* ============================================================ */
void example2_strcpy(void) {
printf("\n=== EXAMPLE 2: strcpy() and strncpy() ===\n\n");
char src[] = "Hello, World!";
char dest1[20];
char dest2[10];
char dest3[20];
// strcpy - copies until null terminator
strcpy(dest1, src);
printf("strcpy(dest, \"Hello, World!\"):\n");
printf(" Result: \"%s\"\n\n", dest1);
// strncpy with truncation
strncpy(dest2, src, sizeof(dest2) - 1);
dest2[sizeof(dest2) - 1] = '\0'; // Ensure null termination!
printf("strncpy(dest, src, 9) + null terminate:\n");
printf(" Result: \"%s\" (truncated)\n\n", dest2);
// strncpy with padding
memset(dest3, 'X', sizeof(dest3)); // Fill with X for visibility
strncpy(dest3, "Hi", 10);
printf("strncpy(dest, \"Hi\", 10):\n");
printf(" Pads with nulls: ");
for (int i = 0; i < 12; i++) {
if (dest3[i] == '\0') printf("\\0 ");
else printf("%c ", dest3[i]);
}
printf("\n");
}
/* ============================================================
* EXAMPLE 3: strcat() and strncat()
* ============================================================ */
void example3_strcat(void) {
printf("\n=== EXAMPLE 3: strcat() and strncat() ===\n\n");
char str1[30] = "Hello";
char str2[20] = "Hello";
// strcat
strcat(str1, ", World!");
printf("strcat(\"Hello\", \", World!\"):\n");
printf(" Result: \"%s\"\n\n", str1);
// strncat - appends at most n characters
strncat(str2, ", World!", 7);
printf("strncat(\"Hello\", \", World!\", 7):\n");
printf(" Result: \"%s\"\n\n", str2);
// Safe concatenation pattern
char buffer[20] = "Hi";
size_t remaining = sizeof(buffer) - strlen(buffer) - 1;
strncat(buffer, " there my friend", remaining);
printf("Safe concatenation with remaining space:\n");
printf(" Result: \"%s\"\n", buffer);
}
/* ============================================================
* EXAMPLE 4: strcmp() and strncmp()
* ============================================================ */
void example4_strcmp(void) {
printf("\n=== EXAMPLE 4: strcmp() and strncmp() ===\n\n");
printf("strcmp() return values:\n\n");
// Equal strings
printf(" strcmp(\"abc\", \"abc\") = %d (equal)\n",
strcmp("abc", "abc"));
// First is less
printf(" strcmp(\"abc\", \"abd\") = %d (abc < abd)\n",
strcmp("abc", "abd"));
// First is greater
printf(" strcmp(\"abd\", \"abc\") = %d (abd > abc)\n",
strcmp("abd", "abc"));
// Shorter string
printf(" strcmp(\"ab\", \"abc\") = %d (ab < abc)\n",
strcmp("ab", "abc"));
printf("\nstrncmp() - Compare first n characters:\n\n");
printf(" strncmp(\"Hello World\", \"Hello There\", 5) = %d\n",
strncmp("Hello World", "Hello There", 5));
printf(" strncmp(\"Hello World\", \"Hello There\", 7) = %d\n",
strncmp("Hello World", "Hello There", 7));
printf("\nUsage pattern:\n");
printf(" if (strcmp(s1, s2) == 0) { /* strings equal */ }\n");
}
/* ============================================================
* EXAMPLE 5: strchr() and strrchr()
* ============================================================ */
void example5_strchr(void) {
printf("\n=== EXAMPLE 5: strchr() and strrchr() ===\n\n");
const char *str = "Hello World";
printf("String: \"%s\"\n\n", str);
// strchr - find first occurrence
char *first = strchr(str, 'o');
if (first) {
printf("strchr(str, 'o'):\n");
printf(" Found at position: %ld\n", first - str);
printf(" Substring: \"%s\"\n\n", first);
}
// strrchr - find last occurrence
char *last = strrchr(str, 'o');
if (last) {
printf("strrchr(str, 'o'):\n");
printf(" Found at position: %ld\n", last - str);
printf(" Substring: \"%s\"\n\n", last);
}
// Character not found
char *notfound = strchr(str, 'x');
printf("strchr(str, 'x'): %s\n", notfound ? notfound : "NULL");
}
/* ============================================================
* EXAMPLE 6: strstr() - Find Substring
* ============================================================ */
void example6_strstr(void) {
printf("\n=== EXAMPLE 6: strstr() ===\n\n");
const char *str = "The quick brown fox jumps over the lazy dog";
printf("String: \"%s\"\n\n", str);
// Find substring
char *result = strstr(str, "brown");
if (result) {
printf("strstr(str, \"brown\"):\n");
printf(" Found at position: %ld\n", result - str);
printf(" Rest of string: \"%s\"\n\n", result);
}
// Find another
result = strstr(str, "the");
if (result) {
printf("strstr(str, \"the\"):\n");
printf(" First occurrence at: %ld\n", result - str);
}
// Not found
result = strstr(str, "cat");
printf("\nstrstr(str, \"cat\"): %s\n", result ? result : "NULL");
}
/* ============================================================
* EXAMPLE 7: strspn() and strcspn()
* ============================================================ */
void example7_strspn(void) {
printf("\n=== EXAMPLE 7: strspn() and strcspn() ===\n\n");
// strspn - length of initial match
printf("strspn() - Length of initial matching segment:\n\n");
printf(" strspn(\"hello123\", \"helo\") = %zu\n",
strspn("hello123", "helo"));
printf(" strspn(\"123abc\", \"0123456789\") = %zu\n",
strspn("123abc", "0123456789"));
printf(" strspn(\"aaabbbccc\", \"a\") = %zu\n\n",
strspn("aaabbbccc", "a"));
// strcspn - length of initial NON-matching segment
printf("strcspn() - Length until any character from reject:\n\n");
printf(" strcspn(\"hello123\", \"0123456789\") = %zu\n",
strcspn("hello123", "0123456789"));
printf(" strcspn(\"hello\\nworld\", \"\\n\") = %zu\n\n",
strcspn("hello\nworld", "\n"));
// Common use: remove newline from fgets input
printf("Common pattern - Remove newline:\n");
char input[] = "Hello World\n";
printf(" Before: \"%s\" (with newline)\n", input);
input[strcspn(input, "\n")] = '\0';
printf(" After: \"%s\" (newline removed)\n", input);
}
/* ============================================================
* EXAMPLE 8: strtok() - Tokenization
* ============================================================ */
void example8_strtok(void) {
printf("\n=== EXAMPLE 8: strtok() ===\n\n");
// Basic tokenization
char str1[] = "apple,banana,cherry,date";
printf("Tokenizing \"%s\" with \",\":\n\n", "apple,banana,cherry,date");
char *token = strtok(str1, ",");
int count = 1;
while (token != NULL) {
printf(" Token %d: \"%s\"\n", count++, token);
token = strtok(NULL, ","); // NULL for subsequent calls
}
// Multiple delimiters
printf("\nMultiple delimiters:\n");
char str2[] = "Hello, World! How are you?";
printf("String: \"%s\"\n", "Hello, World! How are you?");
printf("Delimiters: \" ,!?\"\n\n");
token = strtok(str2, " ,!?");
count = 1;
while (token != NULL) {
printf(" Token %d: \"%s\"\n", count++, token);
token = strtok(NULL, " ,!?");
}
printf("\nWARNING: strtok modifies the original string!\n");
}
/* ============================================================
* EXAMPLE 9: memset(), memcpy(), memmove()
* ============================================================ */
void example9_mem_functions(void) {
printf("\n=== EXAMPLE 9: Memory Functions ===\n\n");
// memset - fill memory
char buffer[20];
memset(buffer, '-', 19);
buffer[19] = '\0';
printf("memset(buffer, '-', 19):\n");
printf(" Result: \"%s\"\n\n", buffer);
// memset with zeros
int arr[5] = {1, 2, 3, 4, 5};
printf("Before memset: [%d, %d, %d, %d, %d]\n",
arr[0], arr[1], arr[2], arr[3], arr[4]);
memset(arr, 0, sizeof(arr));
printf("After memset to 0: [%d, %d, %d, %d, %d]\n\n",
arr[0], arr[1], arr[2], arr[3], arr[4]);
// memcpy - copy memory
char src[] = "Hello World";
char dest[20];
memcpy(dest, src, strlen(src) + 1);
printf("memcpy(dest, \"Hello World\", 12):\n");
printf(" Result: \"%s\"\n\n", dest);
// memmove - safe for overlapping regions
char overlap[] = "Hello World";
printf("memmove for overlapping regions:\n");
printf(" Before: \"%s\"\n", overlap);
memmove(overlap + 6, overlap, 5);
overlap[11] = '\0';
printf(" After memmove(str+6, str, 5): \"%s\"\n", overlap);
}
/* ============================================================
* EXAMPLE 10: memcmp() and memchr()
* ============================================================ */
void example10_memcmp_memchr(void) {
printf("\n=== EXAMPLE 10: memcmp() and memchr() ===\n\n");
// memcmp
char a[] = "Hello";
char b[] = "Hello";
char c[] = "Help!";
printf("memcmp() - Compare memory blocks:\n\n");
printf(" memcmp(\"Hello\", \"Hello\", 5) = %d\n", memcmp(a, b, 5));
printf(" memcmp(\"Hello\", \"Help!\", 5) = %d\n", memcmp(a, c, 5));
printf(" memcmp(\"Hello\", \"Hello\", 3) = %d\n\n", memcmp(a, b, 3));
// memchr
char str[] = "Hello World";
printf("memchr() - Find byte in memory:\n\n");
char *ptr = memchr(str, 'W', strlen(str));
if (ptr) {
printf(" memchr(str, 'W', 11): Found at position %ld\n", ptr - str);
}
ptr = memchr(str, 'x', strlen(str));
printf(" memchr(str, 'x', 11): %s\n", ptr ? "Found" : "NULL");
}
/* ============================================================
* EXAMPLE 11: sprintf() and snprintf()
* ============================================================ */
void example11_sprintf(void) {
printf("\n=== EXAMPLE 11: sprintf() and snprintf() ===\n\n");
char buffer[100];
int num = 42;
float pi = 3.14159;
// sprintf - format to string
sprintf(buffer, "Number: %d, Pi: %.2f", num, pi);
printf("sprintf(buffer, \"Number: %%d, Pi: %%.2f\", 42, 3.14159):\n");
printf(" Result: \"%s\"\n\n", buffer);
// snprintf - safe with size limit
char small[15];
int written = snprintf(small, sizeof(small), "Hello, World! This is a long message.");
printf("snprintf with buffer size 15:\n");
printf(" Result: \"%s\"\n", small);
printf(" Would have written: %d characters\n", written);
printf(" Actually wrote: %zu characters\n\n", strlen(small));
// Building complex strings
char path[100];
snprintf(path, sizeof(path), "/home/%s/documents/%s.txt", "user", "file");
printf("Building path:\n");
printf(" Result: \"%s\"\n", path);
}
/* ============================================================
* EXAMPLE 12: sscanf() - Parse String
* ============================================================ */
void example12_sscanf(void) {
printf("\n=== EXAMPLE 12: sscanf() ===\n\n");
// Parse multiple values
char data[] = "42 3.14 Hello";
int i;
float f;
char word[20];
int count = sscanf(data, "%d %f %s", &i, &f, word);
printf("Parsing \"%s\":\n", data);
printf(" Items parsed: %d\n", count);
printf(" Integer: %d\n", i);
printf(" Float: %.2f\n", f);
printf(" String: \"%s\"\n\n", word);
// Parse with format
char date[] = "2024-03-15";
int year, month, day;
sscanf(date, "%d-%d-%d", &year, &month, &day);
printf("Parsing date \"%s\":\n", date);
printf(" Year: %d, Month: %d, Day: %d\n\n", year, month, day);
// Parse CSV-like data
char csv[] = "John,25,Engineer";
char name[20];
int age;
char job[30];
sscanf(csv, "%[^,],%d,%s", name, &age, job);
printf("Parsing CSV \"%s\":\n", csv);
printf(" Name: %s, Age: %d, Job: %s\n", name, age, job);
}
/* ============================================================
* EXAMPLE 13: strpbrk() - Find Any Character
* ============================================================ */
void example13_strpbrk(void) {
printf("\n=== EXAMPLE 13: strpbrk() ===\n\n");
const char *str = "Hello, World! 123";
printf("String: \"%s\"\n\n", str);
// Find first vowel
char *ptr = strpbrk(str, "aeiouAEIOU");
if (ptr) {
printf("First vowel: '%c' at position %ld\n", *ptr, ptr - str);
}
// Find first digit
ptr = strpbrk(str, "0123456789");
if (ptr) {
printf("First digit: '%c' at position %ld\n", *ptr, ptr - str);
}
// Find first punctuation
ptr = strpbrk(str, ",.!?;:");
if (ptr) {
printf("First punctuation: '%c' at position %ld\n", *ptr, ptr - str);
}
}
/* ============================================================
* EXAMPLE 14: Safe String Functions Pattern
* ============================================================ */
void example14_safe_patterns(void) {
printf("\n=== EXAMPLE 14: Safe Function Patterns ===\n\n");
// Safe copy
printf("Safe copy pattern:\n");
char dest[10];
const char *src = "Hello, World!";
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
printf(" Source: \"%s\"\n", src);
printf(" Dest[10]: \"%s\" (truncated safely)\n\n", dest);
// Safe concatenation
printf("Safe concatenation pattern:\n");
char buffer[20] = "Hello";
const char *append = " World and more!";
size_t current_len = strlen(buffer);
size_t remaining = sizeof(buffer) - current_len - 1;
strncat(buffer, append, remaining);
printf(" Result: \"%s\"\n\n", buffer);
// Safe formatting
printf("Safe formatting pattern:\n");
char formatted[15];
int needed = snprintf(formatted, sizeof(formatted),
"Value: %d%%", 100);
printf(" Result: \"%s\"\n", formatted);
printf(" Needed: %d, Got: %zu\n", needed, strlen(formatted));
if (needed >= (int)sizeof(formatted)) {
printf(" WARNING: Truncation occurred!\n");
}
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
int main() {
printf("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
printf("ā STRING FUNCTIONS - EXAMPLES ā\n");
printf("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n\n");
example1_strlen();
example2_strcpy();
example3_strcat();
example4_strcmp();
example5_strchr();
example6_strstr();
example7_strspn();
example8_strtok();
example9_mem_functions();
example10_memcmp_memchr();
example11_sprintf();
example12_sscanf();
example13_strpbrk();
example14_safe_patterns();
printf("\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
printf("All examples completed!\n");
printf("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
return 0;
}