在 c++ 中查找字符串中没有循环的数字总和

Find sum of numbers in a string without loops in c++

本文关键字:数字 循环 c++ 查找 字符串      更新时间:2023-10-16

我在网上找到了大量资源,如何计算字母数字字符串中的数字总和,下面我有一个有效的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; 
}