C++ 如何将字符保存到字符数组中
所以我想知道如何在字符数组中保存字符。像这样的C++ 如何将字符保存到字符数组中,c++,C++,所以我想知道如何在字符数组中保存字符。像这样的 int const l=100; 字符a[l]; 字符b[l] cin.getline(a,l); int d; d=斯特伦(a); int i=0; 对于(i=0;i,如果不使用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] ==
int const l=100;
字符a[l];
字符b[l]
cin.getline(a,l);
int d;
d=斯特伦(a);
int i=0;
对于(i=0;i,如果不使用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';
首先,如果你真的在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;
}
#包括
#包括
int main(int argc,char*argv[])
{
std::字符串s,s1;
标准::getline(标准::cin,s);
对于(int i=0;i std::不能只使用std::copy_if
,或者std::remove_if
如果你不需要a
来做其他事情。@chris:我怀疑初学者是否能使用它。@KarolyHorvath,一些例子和解释,也许还有。
auto it = std::copy_if(&a[0], &a[d], &b[0], [](char c){ return c == 'a'; });
*it = '\0';
#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;
}