Program to Convert String to Char Array in C++
String to Char Array :
String is defined as the sequence of characters while char array is defined as the array of characters.Here we will convert string into character array.
How to Convert String to Char Array in C++ :
In general, String can converted into char array by using loop or also by other method.
Below are the two techniques to convert string to char array in C++ :
Method 1 :
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { string str = "PrepInsta"; int n = str.length(); // size of string char* arr = new char[n+1]; //declaring a character array for(int i=0;i < n;i++){ arr[i] = str[i]; } arr[n] = '\0'; cout< < "The character array is : "< < arr; return 0; }
Output :
The character array is : PrepInsta
In the above program, we traverse the string using for loop and store the particular character of string into the char array.
Method 2:
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { string str = "PrepInsta"; char* arr = &str[0]; //declaring a character array and assign it with address of string cout<<"The character array is : "< < arr; return 0; }
Output :
The character array is : PrepInsta
In the above program, we directly assign the address of 1st character of string to a pointer of char array.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment