简体   繁体   English

计算字符串中所有数字的总和

[英]Compute the sum of all numbers in a string

I'm working on this program, it asked me to compute the sum of all numbers in a string.我正在开发这个程序,它要求我计算字符串中所有数字的总和。 For example:例如:

Input: There are 10 chairs, 4 desks, and 2 fans.  
Output: 16  
Explanation: 10 + 4 + 2 = 16

My program is like this:我的程序是这样的:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "There are 10 chairs, 4 desks, and 2 fans.";
    int sum = 0;

    for(int i = 0; i < str.size(); i++)
    {
        if(str[i] >= 0 && str[i] <= 9)
            sum += (int)str[i];
    }
    cout << sum << endl;
}

I don't understand why the output of my program is 0 , can someone explain what's wrong with my program.我不明白为什么我的程序的 output 是0 ,有人可以解释我的程序出了什么问题。 Thank you谢谢

You should use ascii code to find the numbers in string .您应该使用ascii代码来查找string中的数字。 the 0 ascii code is 48 and 9 is 57 . 0 ascii代码是48957 after find the number in string you should make whole number for example 10 is 1 and 0 .string中找到数字后,您应该制作整数,例如1010 and you should make string with value "10" and use stoi to convert it to int .并且您应该使用值为“10”string并使用stoi将其转换为int

  int main()
    {
        string str = "There are 10 chairs, 4 desks, and 2 fans.";
        int sum = 0;
        string number;
        bool new_number = false , is_number ;
        for (int i = 0; i < str.size(); i++)
        {
            // if you use ascii it is good. 
           //but if you use other character encodings.you should use if (str[i] >= '0' && str[i] <= '9')
            if (str[i] >= 48 && str[i] <= 57)
            {
                number += str[i];
                if (!(str[i+1] >= 48 && str[i+1] <= 57))
                {
                    
                        sum += stoi(number);
                        number = "";
                }
            }
           
          
        }
        cout << sum << endl;
    }

Alternatively you could use regex, because everyone loves regex.或者你可以使用正则表达式,因为每个人都喜欢正则表达式。

int main() {
  std::string str = "There are 10 chairs, 4 desks, and 2 fans.";

  std::regex number_regex("(\\d+)");

  auto begin = std::sregex_iterator(str.begin(), str.end(), number_regex);
  auto end   = std::sregex_iterator();

  int sum = 0;
  for (auto i = begin; i != end; ++i) {
    auto m = *i;
    sum += std::stoi(m.str());
  }

  std::cout << sum << "\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM