c++ - 如何将字符保存到字符数组中

标签 c++

所以我想知道如何将字符保存在一个字符数组中。像这样。


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}

我不知道是否有一个函数可以做到这一点,甚至我应该如何处理它。

最佳答案

首先,如果您真的用 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;
}

关于c++ - 如何将字符保存到字符数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20838056/

相关文章:

c++ - 打印小于 100 的质数

java - 在 c++/c 中使用 JAR 文件

c++ - 为什么 switch 构造中的声明是合法的?

c++ - *&++i 会在 C++03 中导致未定义的行为吗?

c++ - 如何获取所有子节点值

C++ 点作为空格?

c++ - 变量在不同的范围内被取消引用

c++ - 在c++中,我们能否通过volatile +内存栅栏(sfence + lfence)保证两个线程之间发生事前?

c++ - 为什么 std::find 是这样实现的?

c++ - QListWidget : Event on item click