In C, a string is a sequence of characters terminated by a null character ('\0').
Unlike other programming languages, C does not have a built-in string data type.
Instead, strings are represented as arrays of characters.
1. Declaring Strings
To declare a string in C, you use an array of characters. The size of the array must
be large enough to accommodate the string and the null terminator ('\0').
The syntax for declaring a string is:
char string_name[size];
Example:
#include <stdio.h>
int main() {
char str[20]; // Declaring a string with space for 20 characters
printf("Enter a string: ");
scanf("%s", str); // Reading a string from user input
printf("You entered: %s\n", str); // Printing the string
return 0;
}
In this example, str is an array of characters that can store up to 19 characters
(plus the null character).
2. Initializing Strings
You can initialize a string during its declaration by assigning a string literal (a
sequence of characters enclosed in double quotes).
, Example:
#include <stdio.h>
int main() {
char str[] = "Hello, World!"; // Initializing a string with a string literal
printf("%s\n", str); // Output: Hello, World!
return 0;
}
Here, str[] is automatically sized to fit the string "Hello, World!" (including the null
terminator).
3. Accessing String Elements
Strings in C are arrays of characters, so you can access individual characters using
an index, similar to how you access array elements.
Example:
#include <stdio.h>
int main() {
char str[] = "Hello";
printf("First character: %c\n", str[0]); // Output: H
printf("Third character: %c\n", str[2]); // Output: l
return 0;
}
In this example, str[0] gives the first character ('H'), and str[2] gives the third
character ('l').