Convert a Character Array into a String in C
In C, a character array can be converted into a string by ensuring it is null-terminated or by using standard library functions like strcpy()
or sprintf()
.
Strings in C are represented as arrays of characters ending with a null character '\0'
.
In this tutorial, we cover different ways to convert a character array into a string.
Examples of Converting a Character Array into a String
1. Adding a Null Terminator Manually
In this example, we will manually add a null terminator ('\0'
) at the end of a character array to make it a valid C string.
main.c
#include <stdio.h>
int main() {
char charArray[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("String: %s\n", charArray);
return 0;
}
Explanation:
- We declare a character array
charArray
with 6 elements, including the null terminator'\0'
. - The null terminator explicitly marks the end of the string, making it a valid C string.
- The
printf()
function prints the character array as a string.
Output:
String: Hello
2. Using strcpy()
to Copy a Character Array
In this example, we will use the strcpy()
function from the string.h
library to copy a character array into a string.
main.c
#include <stdio.h>
#include <string.h>
int main() {
char charArray[] = {'W', 'o', 'r', 'l', 'd', '\0'};
char string[10];
strcpy(string, charArray); // Copy charArray to string
printf("String: %s\n", string);
return 0;
}
Explanation:
- We declare a character array
charArray
and ensure it ends with'\0'
. - We declare another character array
string
with enough space to store the copied characters. - We use
strcpy()
to copycharArray
intostring
, making it a valid string. - The
printf()
function prints the converted string.
Output:
String: World
3. Using sprintf()
for Conversion
In this example, we will use sprintf()
to format a character array into a string.
main.c
#include <stdio.h>
int main() {
char charArray[] = "C Programming"; // Implicitly null-terminated
char string[20];
sprintf(string, "%s", charArray); // Format the character array into a string
printf("String: %s\n", string);
return 0;
}
Explanation:
- The character array
charArray
is initialized as a string, which means it already includes the'\0'
terminator. - We declare a character array
string
with enough space to store the formatted text. sprintf()
copies the contents ofcharArray
intostring
using formatted output.- The
printf()
function prints the resulting string.
Output:
String: C Programming
Conclusion
In this tutorial, we covered different ways to convert a character array into a string in C:
- Manually adding a null terminator: Ensuring the character array ends with
'\0'
makes it a string. - Using
strcpy()
: The standardstring.h
function copies a character array into another, converting it into a string. - Using
sprintf()
: This function formats and stores characters into a string.
Each method is useful depending on the scenario, but ensuring the presence of a null terminator is key to proper string handling in C.