Reputation: 135
So i would like to know how to save characters in a char array. something like this.
int const l=100;
char a[l];
char b[l]
cin.getline(a,l);
int d;
d=strlen (a);
int i=0;
for(i=0;i<d;i++)
{
if(a[i]=='a')
{do something so i can save only the items that match the
criteria in the new char array}
I don't know if there is a function to do this or even how i should approach it .
Upvotes: 0
Views: 2595
Reputation: 217145
This may help if you don't use STL:
int j = 0; // index for b. An array will be filled from the zero element
for (int i = 0; i < d; i++)
{
if (a[i] == 'a') // or any filter criter
{
b[j] = a[i];
++j;
}
}
b[j] = '\0';
With STL (and C++11):
auto it = std::copy_if(&a[0], &a[d], &b[0], [](char c){ return c == 'a'; });
*it = '\0';
Upvotes: 1
Reputation: 25927
First of all, if you really write in C++, avoid arrays. They are tougher to handle than objects really created for array or string handling, such as std::string
.
Try this one:
#include <string>
#include <iostream>
int main(int argc, char * argv[])
{
std::string s, s1;
std::getline(std::cin, s);
for (int i = 0; i < s.length(); i++)
{
if (s[i] == 'a')
s1.push_back(s[i]);
}
std::cout << "Processed string: " << s1;
}
Upvotes: 1