How to 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 multiple different ways

Type1

Algorithm

Begin
   Assign a string value to a char array variable m.
   Define and string variable str
   For i = 0 to sizeof(m)
      Copy character by character from m to str.
      Print character by character from str.
End

Example

#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

#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

Type3

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

#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 30-Apr-2019 11:06:58
Advertisements