我需要使用库字符串函数和不使用它们来解决这个任务。
我解决了没有特殊功能:
void without_functions(string str)
{
int* how_many_num = new int[10];
for (int i = 0; i < 10; ++i)
how_many_num[i] = 0;
for (int i = 0; i < str.size(); ++i)
{
if (str[i] >= '0' && str[i] <= '9')
{
++how_many_num[int(str[i]) - 48];
}
}
for (int i = 0; i <= 9; ++i)
{
if (how_many_num[i] != 0)
{
cout << "Digit " << i << " is founded" << how_many_num[i] << " times" << endl;
}
}
for (int i = 0; i < str.size(); ++i)
{
if ((int(str[i]) >= 65 && int(str[i]) <= 90) || (int(str[i]) >= 97 && str[i] <= '122'))
{
str[i] = ' ';
}
}
cout << endl << "New string: " << str << endl;
}
字符串
我想不出如何用字符串函数(方法)来实现这个任务。
2条答案
按热度按时间xesrikrc1#
without_functions()
有很多问题:how_many_num
,使用完需要delete[]
,最好用std::vector
,但对于这么小的数组,使用动态内存没有意义,使用固定数组即可cout
循环不允许0
数字。您应该使用0..9
以外的初始值填充数组元素,然后查找该值而不是0
。122
的时候却在寻找'122'
。然而,你真的应该使用字符而不是数字ASCII码。在编码中使用magic numbers是一个坏习惯。现在,尝试一些更像这样的东西:
字符串
现在,要将其转换为标准库函数,请尝试以下操作:
型
或者:
型
5w9g7ksd2#
有些用户可能会在使用“使用库字符串函数”这一短语时感到困惑。我只假设你指的是标准库函数。
有几种方法可以实现这一点:
std::replace_if
和std::isdigit
1.最新ranges replace
1.你也可以使用string direct
replace
函数--但我不推荐在这种练习中使用它。选择你最喜欢的,我建议学习所有的。