Open In App

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

Last Updated : 15 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Declare a pointer to a constant character, and initialize it with the string you want to convert.
  • Declare a character array that will hold the converted string but make sure it’s large enough to hold the source string and the null terminator.
  • Use the strcpy() function to copy the source string to the destination character array including the null terminator.
  • Finally, print the character array.

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
// 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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads