1. What is a Character Array?
A character
array is simply an array where the data type of the elements is char. It is used to store a sequence of
characters.
Declaration:
// Declares a character array that can hold 20 characters
char city[20];
This is the fundamental building block for strings in C.
2. What is a "String" in C?
In C, a string is not a built-in data type (like in Java or Python). Instead, a string is a convention.
A C-string is
a character array that is terminated by a special
character called the "null terminator", which
is written as '\0'.
This '\0' character acts as a "sentinel
value" or a marker that tells functions (like printf, strlen, etc.) where the string officially ends, regardless of the
array's total size.
Example: To store the string "Hi" (which has 2 letters), you need a character array of size 3.
·
name[0]
= 'H'
·
name[1]
= 'i'
·
name[2]
= '\0' (The null terminator)
Crucial Difference: strlen vs. sizeof
·
char
name[10] = "Hi";
·
sizeof(name): This
gives the total memory allocated to the array. Result is 10 (bytes).
·
strlen(name): This
is a function (from <string.h>) that
counts characters until it finds the \0. Result is 2.
3. Initializing Character Arrays (Strings)
There are two main ways to initialize a character array to hold a string.
// Method 1: The "long way" (rarely used)
// You must manually add the null terminator.
char str1[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
// Method 2: The "string literal" shortcut (very common)
// The compiler automatically adds the null terminator '\0' at the end.
char str2[6] = "Hello";
// You can also let the compiler set the size:
char str3[] = "Hello"; // Compiler makes this array size 6 (5 letters + '\0')
4. Reading and Writing Strings
You use printf and scanf (or fgets) with the %s format specifier to work with
strings.
Writing a String:
char city[] = "London";
printf("The city is: %s\n", city);
Reading a String (Two Ways)
Method 1: `scanf` (Basic, but Unsafe)
scanf is simple but has two major problems:
1. It stops
reading at the first whitespace (space, tab, or newline). If you
type "New York", scanf will
only read "New".
2. It can
cause a buffer overflow. If you declare char name[10]; and the user types a
20-character name, scanf will
write data past the array's boundary, corrupting memory.
char name[20];
printf("Enter your name: ");
scanf("%s", name); // No & is needed for a string in scanf
printf("Your name is: %s\n", name);
Method 2: `fgets` (Advanced, Much Safer)
fgets ("file get string") is the recommended way to read
strings. It is safer because it limits the number of characters read.
· It reads an entire line, including spaces.
· It is safe from buffer overflows.
·
It has one small catch: it also reads and stores the
'Enter' key (the newline character \n).
char address[50];
printf("Enter your address: ");
// Parameters:
// 1. The array to store the string in (address)
// 2. The maximum size to read (sizeof(address)) - THIS MAKES IT SAFE
// 3. The input source (stdin means "standard input", the keyboard)
fgets(address, sizeof(address), stdin);
printf("Your address is: %s", address);
5. Basic Example Program (scanf vs. fgets)
/* * Example 1: Basic String I/O * Demonstrates the difference between scanf and fgets.*/
#include <stdio.h>
int main() {
char food[20];
// 1. Using scanf (try typing "ice cream")
printf("Enter your favorite food (using scanf): ");
scanf("%s", food);
printf("Scanf read: %s\n", food); // Will only print "ice"
// Clear the input buffer (advanced, but needed after scanf)
while (getchar() != '\n');
// 2. Using fgets (try typing "ice cream" again)
printf("\nEnter your favorite food (using fgets): ");
fgets(food, sizeof(food), stdin);
printf("Fgets read: %s", food); // Will print "ice cream" (and a newline)
return 0;
}6. Built-in String Functions (Advanced)
To use these
functions, you must include the string header file: #include
<string.h>
These functions are powerful and perform operations on null-terminated strings.
1. strlen(str) - String Length
o Calculates
the length of a string (stops at \0).
o Returns
an integer (size_t type).
o strlen("Hello") returns
5.
2. strcpy(dest, src) - String Copy
o Copies
the string from src (source)
into dest (destination).
o Warning: dest must be large enough to hold src!
o You cannot copy
strings using =.
(e.g., str1 = str2; is
an error).
3. strcat(dest, src) - String Concatenate
o Joins
(appends) the src string
to the end of the dest string.
o The
first character of src overwrites
the \0 of dest.
o Warning: dest must be large enough to hold the
combined string.
4. strcmp(str1, str2) - String Compare
o Compares two strings lexicographically (like in a dictionary).
o You cannot compare
strings using ==.
(e.g., if (str1 ==
str2) is an error).
o Returns:
§ 0 if str1 is equal to str2.
§ < 0 (a
negative number) if str1 comes before str2.
§ > 0 (a
positive number) if str1 comes after str2.
7. Advanced Example Program (Using <string.h>)
/* * Example 2: Advanced String Manipulation * Demonstrates the use of strlen, strcpy, strcat, and strcmp * from the <string.h> library.*/
#include <stdio.h>
#include <string.h> // Must include this!
int main() {
char firstName[50];
char lastName[50];
char fullName[100]; // Must be large enough for both!
// 1. Get first name
printf("Enter your first name: ");
fgets(firstName, sizeof(firstName), stdin);
// 2. Get last name
printf("Enter your last name: ");
fgets(lastName, sizeof(lastName), stdin);
// 3. Remove the newline ('\n') from fgets results
// strcspn finds the first newline and we replace it with \0
firstName[strcspn(firstName, "\n")] = '\0';
lastName[strcspn(lastName, "\n")] = '\0';
// 4. Combine the strings using strcpy and strcat
// First, copy the first name into the empty fullName
strcpy(fullName, firstName);
// Second, concatenate a space " " onto the end of fullName
strcat(fullName, " ");
// Third, concatenate the last name onto the end of fullName
strcat(fullName, lastName);
// 5. Print the result and its length
printf("\nYour full name is: %s\n", fullName);
printf("Your name has %d characters (excluding null).\n", (int)strlen(fullName));
// 6. Compare two strings using strcmp
char pass1[] = "apple";
char pass2[] = "apple";
if (strcmp(pass1, pass2) == 0) {
printf("\nThe strings 'apple' and 'apple' are identical.\n");
} else {
printf("\nThe strings are different.\n");
} return 0;
}