Array of Strings C Program
In C programming, a single string is an array of characters.
In fact, an array of strings is an array of character arrays.
Each element of an array of strings is a character array.
It allows to store and manipulate multiple strings.
You can iterate over the elements of a string array.
Create an array of strings
An array of strings has been created in one line using array declaration syntax in the following example:
Examples of creating an array of strings
xxxxxxxxxx
const char* fruits[] = { "Apple", "Banana", "Cherry", "Orange", "Watermelon" };
1. const char* fruits[]
declares an array of character pointers. const char*
means "pointer to a constant character". fruits[]
declares an array named fruits.
2. The array is initialized with the string literals "Apple", "Banana", "Cherry", "Orange", and "Watermelon"
.
The array can be used to access and manipulate these strings.
Loop (iterate) through a string array in C
In C programming, you can loop through a string array in C as demonstrated in the following example:
Example of looping through an array of strings
xxxxxxxxxx
#include <stdio.h>
int main() {
// Creating a string array in one line using array declaration syntax
const char* fruits[] = { "Apple", "Banana", "Cherry", "Orange", "Watermelon" };
int numFruits = sizeof(fruits) / sizeof(fruits[0]); // Calculate the number of elements in the array
//loop through the array using 'for' loop
for (int i = 0; i < numFruits; i++) {
printf("%s\n", fruits[i]); // '%s' is the formatter for string
}
return 0;
}
Output of the above example
Apple Banana Cherry Orange Watermelon
Explanation of Example:
1. const char* fruits[] = { "Apple", "Banana", "Cherry", "Orange", "Watermelon" };
: The line declares an array of string using array of character pointers and initializes the array with the string literals "Apple", "Banana", "Cherry", "Orange", and "Watermelon"
.
2. int numFruits = sizeof(fruits) / sizeof(fruits[0]);
: The line calculates the number of elements (length of array) in the 'fruits' array to use it in the 'for' loop.
3. for (int i = 0; i < numFruits; i++)
: The line uses for loop to iterate over the elements of the array.
4. printf("%s\n", fruits[i]);
: It prints the element of the 'fruits' array on the basis of array index at each iteration. '%s' is the formatter for string.