Convert string to char array in C++

C++Server Side ProgrammingProgramming

This is a C++ program to Convert string to char array in C++. This can be done in many ways:

Type 1:

Algorithm

Begin
   Assign value to string m.
   For i = 0 to sizeof(m)
      Print the char array.
End

Example Code

 Live Demo

#include<iostream>
#include<string.h>
using namespace std;
int main() {
   char m[] = "Tutorialspoint";
   string str;
   int i;
   for(i=0;i<sizeof(m);i++) {
      str[i] = m[i];
      cout<<str[i];
   }
   return 0;
}

Type 2:

We can simply call strcpy() function to copy the string to char array.

Algorithm

Begin
   Assign value to string s.
   Copying the contents of the string to char array using strcpy().
End

Example Code

 Live Demo

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
   string str = "Tutorialspoint";
   char c[str.size() + 1];
   strcpy(c, str.c_str());
   cout << c << '\n';
   return 0;
}

Output

Tutorialspoint

Type 3:

We can avoid using strcpy() which is basically used in c by

std::string::copy instead.

Algorithm

Begin
   Assign value to string s.
   copying the contents of the string to char array using copy().
End

Example Code

 Live Demo

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "Tutorialspoint";
   char c[str.size() + 1];
   str.copy(c, str.size() + 1);
   c[str.size()] = '\0';
   cout << c << '\n';
   return 0;
}

Output

Tutorialspoint
raja
Published on 29-Mar-2019 15:00:37
Advertisements