c
examples
examples.cš§c
/**
* Character Arrays and Strings - Examples
*
* This file demonstrates character array and string operations in C.
*
* Compile: gcc examples.c -o examples
* Run: ./examples
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* ============================================================
* EXAMPLE 1: Character Array Basics
* ============================================================ */
void example1_char_arrays(void) {
printf("=== EXAMPLE 1: Character Array Basics ===\n\n");
// Character array (not a string - no null terminator)
char letters[5] = {'H', 'e', 'l', 'l', 'o'};
// String (character array with null terminator)
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// Print character by character
printf("Letters (char by char): ");
for (int i = 0; i < 5; i++) {
printf("%c", letters[i]);
}
printf("\n");
// Print as string (only works with null terminator)
printf("Greeting (as string): %s\n", greeting);
// Character and ASCII value
char ch = 'A';
printf("\nCharacter '%c' has ASCII value %d\n", ch, ch);
// Demonstrating character arithmetic
printf("'A' + 1 = '%c' (ASCII %d)\n", ch + 1, ch + 1);
printf("'a' - 'A' = %d (difference between cases)\n", 'a' - 'A');
}
/* ============================================================
* EXAMPLE 2: String Initialization Methods
* ============================================================ */
void example2_initialization(void) {
printf("\n=== EXAMPLE 2: String Initialization ===\n\n");
// Method 1: String literal (compiler adds \0)
char str1[] = "Hello";
// Method 2: Explicit size (extra space for more content)
char str2[20] = "Hello";
// Method 3: Character by character
char str3[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// Method 4: Empty string
char str4[10] = "";
// Method 5: Pointer to literal (READ-ONLY!)
const char *str5 = "Hello";
printf("str1: \"%s\" (size: %zu, length: %zu)\n",
str1, sizeof(str1), strlen(str1));
printf("str2: \"%s\" (size: %zu, length: %zu)\n",
str2, sizeof(str2), strlen(str2));
printf("str3: \"%s\" (size: %zu, length: %zu)\n",
str3, sizeof(str3), strlen(str3));
printf("str4: \"%s\" (size: %zu, length: %zu) [empty]\n",
str4, sizeof(str4), strlen(str4));
printf("str5: \"%s\" (pointer to literal)\n", str5);
printf("\nNote: sizeof includes \\0, strlen doesn't\n");
}
/* ============================================================
* EXAMPLE 3: String Input and Output
* ============================================================ */
void example3_io(void) {
printf("\n=== EXAMPLE 3: String I/O ===\n\n");
// Output formatting with printf
char name[] = "Alice";
printf("Basic: |%s|\n", name);
printf("Width 10: |%10s| (right-aligned)\n", name);
printf("Width -10: |%-10s| (left-aligned)\n", name);
printf("Precision: |%.3s| (first 3 chars)\n", name);
// Using puts (simpler, adds newline)
printf("\nUsing puts(): ");
puts(name);
// Printing character by character
printf("Char by char: ");
for (int i = 0; name[i] != '\0'; i++) {
putchar(name[i]);
}
putchar('\n');
}
/* ============================================================
* EXAMPLE 4: String Length (strlen)
* ============================================================ */
void example4_strlen(void) {
printf("\n=== EXAMPLE 4: String Length ===\n\n");
char str1[] = "Hello";
char str2[] = "Hello World";
char str3[] = "";
char str4[100] = "Short";
printf("String: \"%s\"\n", str1);
printf(" strlen: %zu\n", strlen(str1));
printf(" sizeof: %zu (includes \\0)\n\n", sizeof(str1));
printf("String: \"%s\"\n", str2);
printf(" strlen: %zu\n\n", strlen(str2));
printf("Empty string: \"%s\"\n", str3);
printf(" strlen: %zu\n\n", strlen(str3));
printf("String in large array: \"%s\"\n", str4);
printf(" strlen: %zu (actual content)\n", strlen(str4));
printf(" sizeof: %zu (allocated space)\n", sizeof(str4));
// Manual strlen implementation
size_t len = 0;
while (str1[len] != '\0') {
len++;
}
printf("\nManual strlen of \"%s\": %zu\n", str1, len);
}
/* ============================================================
* EXAMPLE 5: String Copy (strcpy, strncpy)
* ============================================================ */
void example5_strcpy(void) {
printf("\n=== EXAMPLE 5: String Copy ===\n\n");
char source[] = "Hello, World!";
char dest1[20];
char dest2[8];
// Using strcpy (dangerous if dest too small!)
strcpy(dest1, source);
printf("strcpy result: \"%s\"\n", dest1);
// Using strncpy (safer)
strncpy(dest2, source, sizeof(dest2) - 1);
dest2[sizeof(dest2) - 1] = '\0'; // Ensure null termination
printf("strncpy (7 chars): \"%s\"\n", dest2);
// Copying part of a string
char partial[6];
strncpy(partial, source, 5);
partial[5] = '\0';
printf("First 5 chars: \"%s\"\n", partial);
// Manual copy
char manual[20];
int i = 0;
while (source[i] != '\0') {
manual[i] = source[i];
i++;
}
manual[i] = '\0';
printf("Manual copy: \"%s\"\n", manual);
}
/* ============================================================
* EXAMPLE 6: String Concatenation (strcat, strncat)
* ============================================================ */
void example6_strcat(void) {
printf("\n=== EXAMPLE 6: String Concatenation ===\n\n");
char greeting[50] = "Hello";
printf("Initial: \"%s\"\n", greeting);
// Concatenate with strcat
strcat(greeting, ", ");
printf("After adding ', ': \"%s\"\n", greeting);
strcat(greeting, "World");
printf("After adding 'World': \"%s\"\n", greeting);
strcat(greeting, "!");
printf("After adding '!': \"%s\"\n", greeting);
// Using strncat (safer)
char safe[15] = "Hi";
strncat(safe, " there, how are you?", sizeof(safe) - strlen(safe) - 1);
printf("\nstrncat (limited): \"%s\"\n", safe);
// Building a sentence
char sentence[100] = "";
strcat(sentence, "The ");
strcat(sentence, "quick ");
strcat(sentence, "brown ");
strcat(sentence, "fox.");
printf("Built sentence: \"%s\"\n", sentence);
}
/* ============================================================
* EXAMPLE 7: String Comparison (strcmp, strncmp)
* ============================================================ */
void example7_strcmp(void) {
printf("\n=== EXAMPLE 7: String Comparison ===\n\n");
char str1[] = "apple";
char str2[] = "banana";
char str3[] = "apple";
char str4[] = "Apple";
int result;
// strcmp returns: <0 if s1<s2, 0 if equal, >0 if s1>s2
result = strcmp(str1, str2);
printf("strcmp(\"%s\", \"%s\") = %d", str1, str2, result);
printf(" ā \"%s\" comes %s\n", str1, result < 0 ? "first" : "second");
result = strcmp(str1, str3);
printf("strcmp(\"%s\", \"%s\") = %d", str1, str3, result);
printf(" ā strings are %s\n", result == 0 ? "equal" : "different");
result = strcmp(str1, str4);
printf("strcmp(\"%s\", \"%s\") = %d", str1, str4, result);
printf(" ā case sensitive (lowercase > uppercase in ASCII)\n");
// Compare first n characters
char hello1[] = "Hello World";
char hello2[] = "Hello There";
printf("\nstrncmp(\"%s\", \"%s\", 5) = %d (first 5 match)\n",
hello1, hello2, strncmp(hello1, hello2, 5));
printf("strncmp(\"%s\", \"%s\", 7) = %d (differ at position 6)\n",
hello1, hello2, strncmp(hello1, hello2, 7));
// Using comparison in conditions
char password[] = "secret123";
char input[] = "secret123";
printf("\nPassword check: %s\n",
strcmp(password, input) == 0 ? "MATCH" : "NO MATCH");
}
/* ============================================================
* EXAMPLE 8: Finding in Strings (strchr, strstr)
* ============================================================ */
void example8_search(void) {
printf("\n=== EXAMPLE 8: Searching in Strings ===\n\n");
char str[] = "Hello, World! Hello, C!";
char *p;
// Find first occurrence of character
p = strchr(str, 'W');
if (p != NULL) {
printf("First 'W' found at index %ld: \"%s\"\n", p - str, p);
}
// Find last occurrence of character
p = strrchr(str, 'o');
if (p != NULL) {
printf("Last 'o' found at index %ld: \"%s\"\n", p - str, p);
}
// Find character not in string
p = strchr(str, 'X');
printf("'X' in string: %s\n", p == NULL ? "not found" : "found");
// Find substring
p = strstr(str, "World");
if (p != NULL) {
printf("\n\"World\" found at index %ld: \"%s\"\n", p - str, p);
}
p = strstr(str, "Hello");
if (p != NULL) {
printf("First \"Hello\" at index %ld\n", p - str);
}
// Finding all occurrences
printf("\nAll 'l' positions: ");
p = str;
while ((p = strchr(p, 'l')) != NULL) {
printf("%ld ", p - str);
p++; // Move past found character
}
printf("\n");
}
/* ============================================================
* EXAMPLE 9: Character Classification (ctype.h)
* ============================================================ */
void example9_ctype(void) {
printf("\n=== EXAMPLE 9: Character Classification ===\n\n");
char test[] = "Hello, World! 123";
printf("String: \"%s\"\n\n", test);
printf("Char Alpha Digit Space Upper Lower Punct\n");
printf("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
for (int i = 0; test[i] != '\0'; i++) {
char c = test[i];
printf("'%c' %c %c %c %c %c %c\n",
c,
isalpha(c) ? 'Y' : '-',
isdigit(c) ? 'Y' : '-',
isspace(c) ? 'Y' : '-',
isupper(c) ? 'Y' : '-',
islower(c) ? 'Y' : '-',
ispunct(c) ? 'Y' : '-');
}
// Counting character types
int letters = 0, digits = 0, spaces = 0, punct = 0;
for (int i = 0; test[i] != '\0'; i++) {
if (isalpha(test[i])) letters++;
else if (isdigit(test[i])) digits++;
else if (isspace(test[i])) spaces++;
else if (ispunct(test[i])) punct++;
}
printf("\nCount: %d letters, %d digits, %d spaces, %d punctuation\n",
letters, digits, spaces, punct);
}
/* ============================================================
* EXAMPLE 10: Case Conversion
* ============================================================ */
void example10_case(void) {
printf("\n=== EXAMPLE 10: Case Conversion ===\n\n");
char str[] = "Hello, World! 123";
char upper[50], lower[50];
printf("Original: \"%s\"\n", str);
// Convert to uppercase
for (int i = 0; str[i] != '\0'; i++) {
upper[i] = toupper(str[i]);
}
upper[strlen(str)] = '\0';
printf("Uppercase: \"%s\"\n", upper);
// Convert to lowercase
for (int i = 0; str[i] != '\0'; i++) {
lower[i] = tolower(str[i]);
}
lower[strlen(str)] = '\0';
printf("Lowercase: \"%s\"\n", lower);
// Toggle case
char toggle[50];
for (int i = 0; str[i] != '\0'; i++) {
if (isupper(str[i])) {
toggle[i] = tolower(str[i]);
} else if (islower(str[i])) {
toggle[i] = toupper(str[i]);
} else {
toggle[i] = str[i];
}
}
toggle[strlen(str)] = '\0';
printf("Toggled: \"%s\"\n", toggle);
// Capitalize first letter of each word
char capitalized[50];
strcpy(capitalized, str);
int newWord = 1;
for (int i = 0; capitalized[i] != '\0'; i++) {
if (isspace(capitalized[i])) {
newWord = 1;
} else if (newWord && isalpha(capitalized[i])) {
capitalized[i] = toupper(capitalized[i]);
newWord = 0;
} else {
capitalized[i] = tolower(capitalized[i]);
}
}
printf("Capitalized: \"%s\"\n", capitalized);
}
/* ============================================================
* EXAMPLE 11: String Reversal
* ============================================================ */
void reverseString(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}
void example11_reverse(void) {
printf("\n=== EXAMPLE 11: String Reversal ===\n\n");
char str1[] = "Hello";
char str2[] = "A man a plan a canal Panama";
char str3[] = "12345";
printf("Original: \"%s\"\n", str1);
reverseString(str1);
printf("Reversed: \"%s\"\n\n", str1);
printf("Original: \"%s\"\n", str2);
reverseString(str2);
printf("Reversed: \"%s\"\n\n", str2);
printf("Original: \"%s\"\n", str3);
reverseString(str3);
printf("Reversed: \"%s\"\n", str3);
}
/* ============================================================
* EXAMPLE 12: Palindrome Check
* ============================================================ */
int isPalindrome(const char str[]) {
int left = 0;
int right = strlen(str) - 1;
while (left < right) {
if (str[left] != str[right]) {
return 0;
}
left++;
right--;
}
return 1;
}
void example12_palindrome(void) {
printf("\n=== EXAMPLE 12: Palindrome Check ===\n\n");
char *tests[] = {"radar", "hello", "level", "world", "madam", "12321"};
int n = sizeof(tests) / sizeof(tests[0]);
for (int i = 0; i < n; i++) {
printf("\"%s\" is %sa palindrome\n",
tests[i], isPalindrome(tests[i]) ? "" : "NOT ");
}
}
/* ============================================================
* EXAMPLE 13: Word Count
* ============================================================ */
int countWords(const char str[]) {
int count = 0;
int inWord = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isspace(str[i])) {
inWord = 0;
} else if (!inWord) {
inWord = 1;
count++;
}
}
return count;
}
void example13_word_count(void) {
printf("\n=== EXAMPLE 13: Word Count ===\n\n");
char *sentences[] = {
"Hello World",
" Leading and trailing spaces ",
"One",
" ",
"Multiple spaces between words"
};
int n = sizeof(sentences) / sizeof(sentences[0]);
for (int i = 0; i < n; i++) {
printf("\"%s\"\n ā %d word(s)\n\n",
sentences[i], countWords(sentences[i]));
}
}
/* ============================================================
* EXAMPLE 14: Array of Strings
* ============================================================ */
void example14_string_arrays(void) {
printf("\n=== EXAMPLE 14: Array of Strings ===\n\n");
// Method 1: 2D character array
char names1[4][10] = {
"Alice",
"Bob",
"Charlie",
"Diana"
};
// Method 2: Array of pointers
const char *names2[] = {
"Alice",
"Bob",
"Charlie",
"Diana"
};
printf("2D Array (char names[4][10]):\n");
for (int i = 0; i < 4; i++) {
printf(" [%d]: \"%s\" (allocated: 10 bytes each)\n", i, names1[i]);
}
printf("\nArray of Pointers (char *names[]):\n");
for (int i = 0; i < 4; i++) {
printf(" [%d]: \"%s\" (pointer size: %zu bytes)\n",
i, names2[i], sizeof(names2[i]));
}
// Modifying 2D array (OK)
names1[0][0] = 'a'; // Change 'A' to 'a'
printf("\nAfter modifying 2D array: %s\n", names1[0]);
// Cannot modify string literals through pointer array!
// names2[0][0] = 'a'; // UNDEFINED BEHAVIOR!
}
/* ============================================================
* EXAMPLE 15: Sorting Strings
* ============================================================ */
void example15_sorting(void) {
printf("\n=== EXAMPLE 15: Sorting Strings ===\n\n");
char names[5][20] = {"Charlie", "Alice", "Eve", "Bob", "Diana"};
int n = 5;
printf("Before sorting:\n");
for (int i = 0; i < n; i++) {
printf(" %s\n", names[i]);
}
// Bubble sort for strings
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (strcmp(names[j], names[j + 1]) > 0) {
// Swap strings
char temp[20];
strcpy(temp, names[j]);
strcpy(names[j], names[j + 1]);
strcpy(names[j + 1], temp);
}
}
}
printf("\nAfter sorting:\n");
for (int i = 0; i < n; i++) {
printf(" %s\n", names[i]);
}
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
int main(void) {
printf("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
printf("ā CHARACTER ARRAYS AND STRINGS - EXAMPLES ā\n");
printf("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
example1_char_arrays();
example2_initialization();
example3_io();
example4_strlen();
example5_strcpy();
example6_strcat();
example7_strcmp();
example8_search();
example9_ctype();
example10_case();
example11_reverse();
example12_palindrome();
example13_word_count();
example14_string_arrays();
example15_sorting();
printf("\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
printf("All examples completed!\n");
return 0;
}