如何将字符保存到char数组中

时间:2013-12-30 10:53:07

标签: c++

所以我想知道如何在char数组中保存字符。像这样的东西。


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}

我不知道是否有这样做的功能,甚至我应该如何处理它。

2 个答案:

答案 0 :(得分:1)

如果您不使用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';

使用STL(和C ++ 11):

auto it = std::copy_if(&a[0], &a[d], &b[0], [](char c){ return c == 'a'; });
*it = '\0';

答案 1 :(得分:1)

首先,如果真的用C ++编写,请避免使用数组。它们比真正为数组或字符串处理创建的对象更难处理,例如std::string

试试这个:

#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;
}
相关问题