To concatenate strings in an array in C, you can use a loop to iterate over the array and use the strcat
function from the string.h library to concatenate each string to a result string.
In this example,
arr
.n
to specify the number of elements in the array.result
and initialize it with an empty string.strcat
function to concatenate the current string to result
.#include <stdio.h>
#include <string.h>
void concatenateStrings(char arr[][100], int n, char *result) {
for (int i = 0; i < n; i++) {
strcat(result, arr[i]);
}
}
int main() {
char arr[][100] = {"Hello", " ", "World", "!"};
int n = sizeof(arr) / sizeof(arr[0]);
char result[400] = ""; // Ensure the result array is large enough
concatenateStrings(arr, n, result);
printf("Concatenated string: %s\n", result);
return 0;
}
Concatenated string: Hello World!
In this example,
arr
.n
to specify the number of elements in the array.result
and initialize it with an empty string.strcat
function to concatenate the current string to result
.#include <stdio.h>
#include <string.h>
void concatenateStrings(char arr[][100], int n, char *result) {
for (int i = 0; i < n; i++) {
strcat(result, arr[i]);
}
}
int main() {
char arr[][100] = {"Good", " ", "Morning", ", ", "everyone!"};
int n = sizeof(arr) / sizeof(arr[0]);
char result[400] = ""; // Ensure the result array is large enough
concatenateStrings(arr, n, result);
printf("Concatenated string: %s\n", result);
return 0;
}
Concatenated string: Good Morning, everyone!
In this tutorial, we learned How to Concatenate Strings in Array in C language with well detailed examples.