+ 4

How can we convert an input string in c++ into an array

I want to convert an input string in c++ into an array containing each alphabet of the string as ots independent and individual element. How can we measure or count the no. of elements in an array with no specific limit defided?

27th Oct 2018, 5:36 PM
Shivam Gavandi
Shivam Gavandi - avatar
6 Answers
+ 2
To count the number of elements in a C++ string: std::string::size example: std::cout << mystr.size(); To access elements in a C++ string like an array, use the String Classes operator overload: [] example: std::cout << "1st at [0] = " << mystr[0]; You do not need anything else. Even iterators and conversions are provided.
29th Oct 2018, 11:51 AM
non
+ 14
Well you actually don't need to convert the string into char array as string is also an array of characters like Gordie said. But if you want to convert the string into C-Style string (char array) as there is no string data type in C so you can use the c_str() function of C++.
27th Oct 2018, 8:09 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 8
this would help by simply copying char by char to string array... this would help.... by simply copying a string to character array... // CPP program to convert string  // to char array #include <bits/stdc++.h>   using namespace std;   // driver code int main() {     // assigning value to string s     string s = "geeksforgeeks";       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());            for (int i=0; i<n; i++)       cout << char_array[i];           return 0; } 
27th Oct 2018, 6:41 PM
#DARK_PROGRAMMER_✔
#DARK_PROGRAMMER_✔ - avatar
+ 4
Gordie " [...] why would you want to? " In my experience, you end up with such situations when you discover too late that something is wrong with your program design (if any :D). Then you frantically try to patch up things by googling the problem and possibly lands on SO, and after reading the whole arguments you feel that " YES! That's the one I was looking for! " So, whiteout a second thought, you quickly apply the given prescription to the code and that's when the second wave of confusion begins! Second possible situation might be the lack of the knowledge of what the language (library) has to offer and how it's gonna mitigate/eliminate the effort of the implementation. In this case, again, you probably get drifted to the wrong direction of googling for how reinventing the wheel in your term!
29th Oct 2018, 6:52 AM
Babak
Babak - avatar
+ 1
don't worried about this silly one bcoz, a string is a group of character, it means it also a array...
29th Oct 2018, 12:02 AM
priyesh
priyesh - avatar