OneBite.Dev - Coding blog in a bite size

Convert A String To An Array In C++

Code snippet for how to Convert A String To An Array In C++ with sample and detail explanation

Understanding how to manipulate strings is vital for any C++ developer. In this article, we will explore a simple process: how to convert a string into an array using C++.

Code snippet: String to Array Conversion

Before we begin, let’s have a look at the code snippet for converting a string into an array.

#include <iostream>
#include <string>
  
int main()
{
    std::string str = "Hello, World!";
    int n = str.length();
  
    char char_array[n + 1];
  
    strcpy(char_array, str.c_str());
  
    for (int i = 0; i < n; i++)
        std::cout << char_array[i];
  
    return 0;
}

Save and run the above code. It will output the string as an array of characters.

Code Explanation for String to Array Conversion

Let’s break down the above code to understand what’s happening inside, step by step.

  1. Include Necessary Libraries: Firstly, the and libraries are included. is for input-output stream and the is for using string functions.
#include <iostream>
#include <string>
  1. Main Function: The main() function is where the program starts execution.
int main()
{
  1. String Definition: Here, we declare and initialize a string ‘str’.
std::string str = "Hello, World!";
  1. Determining String Length: Length of the string is determined by using length() function.
int n = str.length();
  1. Character Array: Create a character array of size ‘n+1’ (n is the length of the string).
char char_array[n + 1];
  1. Copying String to Character Array: Copy the contents of ‘str’ to newly created array ‘char_array’ using strcpy() method.
strcpy(char_array, str.c_str());
  1. For Loop: A simple for loop that runs from ‘0’ to ‘n’ and prints each character of the array.
for (int i = 0; i < n; i++)
        std::cout << char_array[i];
  1. Return Statement: Finally, the main function returns 0 indicating successful completion of the program.
    return 0;
}

That’s it, we have successfully converted a string to a character array in a C++ program. Practice this technique to become more familiar with it. Happy coding!

c-plus-plus