A string is not a formal data type like int or float. Instead, it is simply an array of characters that ends with a special character called the null terminator (\0).
The \0 tells C functions (like printf) where the text ends. Without it, the computer would keep reading memory until it crashes!
1. Declaration and Initialization
There are two main ways to create a string:
#include <stdio.h>
int main() {
// Method 1: Array style (Size is automatically calculated as 6: 'H','e','l','l','o','\0')
char greeting[] = "Hello";
// Method 2: Pointer style (String literal)
char *message = "Welcome to C";
printf("%s, %s!\n", greeting, message);
return 0;
}Expected Output:
Hello, Welcome to C!2. Reading Strings from the User
Reading strings can be tricky because scanf stops reading at the first space it encounters.
scanf(): Good for single words.fgets(): The safest way to read a full line (including spaces).
#include <stdio.h>
int main() {
char fullName[50];
printf("Enter your full name: ");
// fgets(variable, size, source)
fgets(fullName, sizeof(fullName), stdin);
printf("Hello, %s", fullName);
return 0;
}Expected Output:
Enter your full name: John Doe
Hello, John Doe3. Standard String Functions (string.h)
To manipulate strings, you must include the <string.h> library. Here are the "Big Four" functions:
Function. Purpose. Example
strlen()Gets the length (excluding \0)strlen("Hi")
strcpy()Copies one string to anotherstrcpy(dest, src)strcat()Catenates (joins) two stringsstrcat(s1, s2)strcmp()Compares two stringsReturns 0 if they are identical.
code example:
#include <stdio.h>
#include <string.h>
int main() {
char s1[20] = "Apple";
char s2[20] = "Banana";
// Compare
if (strcmp(s1, s2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are different.\n");
}
// Join
strcat(s1, " Pie");
printf("Result: %s\n", s1); // Prints "Apple Pie"
return 0;
}Expected Output:
Strings are different.
Result: Apple Pie