Open In App

How to Convert a String to a Char Array in C?

In C strings are represented as arrays of characters terminated by a null character ('\0'). In this article, we will learn how to convert a string to a char array in C.

Example:

Input:
String: "Hello, World!"
Output:
Character Array: Hello, World!

Converting String to Char Array in C

To convert a string to a character array in C we can use the strcpy() function from the <string.h> library that copies the source string, including the null terminator, to the destination character array.

Approach:

C Program to Convert a String to a Char Array

The below example demonstrates how we can convert a string to a char array.

// C Program to Convert a String to a Char Array

#include <stdio.h>
#include <string.h>

int main()
{
    // Source string
    const char* source = "Hello, World!";

    // Destination char array, make sure it's large enough
    char destination[100];

    // Copy the string including the null terminator
    strcpy(destination, source);

    // Print the destination array
    printf("Character array is: %s\n", destination);

    return 0;
}

Output
Character array is: Hello, World!

Time Complexity: O(n), here n is the length of the input string.
Auxilliary Space: O(1)

Article Tags :