Home > Enterprise >  is There some function that make a conversion from string to array in C
is There some function that make a conversion from string to array in C

Time:12-26

string x = "Banana";

How do I convert it to a char like this:

char x[]={'B', 'a', 'n', 'a', 'n', 'a'};

CodePudding user response:

You can follow this way in c to convert a string into array of characters.

#include <iostream>
#include <cstring>
 
using namespace std;

int main()
{
    // assigning value to string s
    string s = "Banana";
 
    int n = s.length();
 
    // declaring character array
    char char_array[n   1];
 
    // copying the contents of the
    // string to char array
    strcpy(char_array, s.c_str());
 
    // this part need to be deleted. This is only for verification.
    for (int i = 0; i < n; i  )
        cout << char_array[i] << endl;
 
    return 0;
}
  • Related