在 c++ 中查找字符串中没有循环的数字总和
Find sum of numbers in a string without loops in c++
我在网上找到了大量资源,如何计算字母数字字符串中的数字总和,下面我有一个有效的c ++代码。
#include <iostream>
using namespace std;
int findSum(string str)
{
string temp = "";
int sum = 0;
for (char ch: str)
{
if (isdigit(ch))
temp += ch;
else
{
sum += atoi(temp.c_str());
temp = "";
}
}
return sum + atoi(temp.c_str());
}
int main()
{
string str = "t35t5tr1ng";
cout << findSum(str);
return 0;
}
对于上面的示例,"t35t5tr1ng">返回"41"。现在我正在尝试做同样的事情,而不使用任何循环。
在我的头顶上,我正在考虑数组,但即便如此,我也不确定如何在没有某种 for 循环的情况下解析数组中的值。 任何建议或帮助将不胜感激!
您可以使用标准算法而不是编写循环。即使它只是一个底层的 for 循环,但它可以通过陈述意图使用户代码更容易理解。
int findSum(string str)
{
// replace all the non-digits with spaces
std::replace_if(str.begin(), str.end(),
[](unsigned char c) {
return !std::isdigit(c);
}, ' ');
// sum up space separated numbers
std::istringstream iss{str};
return std::accumulate(
std::istream_iterator<int>{iss},
std::istream_iterator<int>{}, 0);
}
这是一个演示。
这是使用std::accumulate的另一种解决方案:
#include <numeric>
#include <iostream>
#include <string>
#include <cctype>
int findSum(std::string str)
{
int curVal = 0;
return std::accumulate(str.begin(), str.end(), 0, [&](int total, char ch)
{
// build up the number if it's a digit
if (std::isdigit(static_cast<int>(ch)))
curVal = 10 * curVal + (ch - '0');
else
{
// add the number and reset the built up number to 0
total += curVal;
curVal = 0;
}
return total;
});
}
int main()
{
std::string str = "t35t5tr1ng";
std::cout << findSum(str);
return 0;
}
相关文章:
- 使用fstream对txt文件中的数字进行循环
- 在 c++ 中查找字符串中没有循环的数字总和
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- C++ for 循环,用于反转数字 10 - 99
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 如何使用循环对所有数字求和?
- 循环中的线程 Runnin 用于对 c++ 中的数字求和
- 为什么我的 while 循环永远不会在 C++ 中的数字猜测游戏中结束?
- C++在不使用pow或循环的情况下计算一个数字的幂
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 如果输入数字为负数,如何循环
- 如何循环开关语句直到找到所需的数字?
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- C++ 循环快乐数字 CS101.1X
- 在循环中使用字符串流从几个字符串中提取数字
- 如何制作 arduino 串行循环(连续接收数字)
- 使用 while () 循环从总和中减去数字
- 有什么方法可以在 c++ 中组织"cycling"(循环)数字?
- 我的堆栈使用链表时出错.无法打印数字循环.(C++)