搜索
首页后端开发C++给定一个字符串,求其中连续数字所组成的数的总和

给定一个字符串,求其中连续数字所组成的数的总和

问题陈述

We have given a string str containing the numeric and alphabetical characters. We need to find the sum of all numbers represented by a continuous sequence of digits available in the given string.

示例示例

Input

str = “12were43”

输出

55

Explanation

The sum of 12 and 43 is equal to 55.

Input

str = “1a2c3d”

输出

6

Explanation

1、2和3的和为6。

Input

str = “werderfrewsf”

输出

0

Explanation

It gives 0 in the output as the string contains no digit.

我们解决问题的逻辑是从给定的字符串中提取所有数字并求和。

方法一

In this approach, we will use isDigit() method to check whether the current character is a digit. Also, we multiply the current value of the number by 10 and add the current character to the number if the current character is a digit.

算法

  • 步骤 1 - 将 'number' 和 'sum' 变量初始化为零。

  • Step 2 − Iterate through the string and check current character is between 0-9 using the isDigit() method.

  • 步骤 3 - 如果当前字符是数字,则将数字值乘以10,并加上当前数字值。

  • 第四步 - 如果当前字符不是数字,则将“number”变量的值添加到“sum”变量中,并将“number”变量的值更新为零。

  • Step 5 − Once the iteration of the loop completes, add the value of the ‘number’ to the ‘sum’ variable and return the value of the sum variable.

Example

#include <bits/stdc++.h>
using namespace std;
// function to return the sum of the consecutive number present in the string
int getSumOfDigits(string str){
   // store the current number
   int number = 0;
   // Stores total sum
   int sum = 0;
   // Traverse the string
   for (auto &ch : str){
      // If the current character is between '0' and '9', append it to the number
      if (isdigit(ch)) {
         number = number * 10 + ch - '0';
      } else {
         // 	if the current character is not between '0' and '9', add 'number' to the sum and reset 'number'
         sum += number;
         number = 0;
      }
   }
   // if the number is greater than 0, add it to sum
   sum += number;
   return sum;
}
int main(){
   string str = "6we24er5rd6";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

输出

The sum of consecutive digits in the given string is - 41
  • 时间复杂度 - O(n),因为我们只使用了一个循环。

  • 空间复杂度 − O(1),因为我们不使用任何额外的空间。

Approach 2

In this approach, we use the ASCII values of the character to check whether the current character is a digit. Also, we append characters to the ‘number’ variable until we get digits in the string and use the atoi() method to extract the number from the string.

算法

  • 步骤1 - 定义'number'变量并将其初始化为空字符串。同时,定义'sum'变量并将其初始化为0。

  • Step 2 − Use for loop to traverse the string and get each character of the string.

  • 步骤 3 - 如果 c-‘0’ 大于等于零且小于等于 9,则表示当前字符是一个数字。

  • Step 4 − If the current character is a digit, append it to the ‘number’ string.

  • Step 5 − If the current character is not a digit, use the c_str() method to convert the number string to a character array and pass it as a parameter of the atoi() method to convert the string to a number. Also, update the number string with the “” value.

    The atoi() method returns a number if the string is convertible to a number; Otherwise, it returns zero.

  • Step 6 − Once the iteration of for loop completes, again use the atoi() method to convert the string to a number and add to the sum value.

Example

#include <bits/stdc++.h>
using namespace std;
// function to return the sum of the consecutive numbers present in the string
int getSumOfDigits(string str){
   string number = "";
   // to store the sum of all the consecutive numbers
   int sum = 0;
   // traverse the string
   for (char c : str){
      // if the current character is between 0 to 9
      if (c - '0' >= 0 && c - '0' <= 9){
         // append it to the number string
         number += c;
      }
      // if the current character is an alphabet
      else {
         // convert string to an array of characters and pass it to atoi() function
         sum += atoi(number.c_str());
         // reset temporary string to empty
         number = "";
      }
   }
   // if the number is greater than 0, add it to sum
   sum += atoi(number.c_str());
   return sum;
}
int main(){
   string str = "11aa32bbb5";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

输出

The sum of consecutive digits in the given string is - 48
  • 时间复杂度 - O(N)

  • 空间复杂度 − O(1)

方法三

在这种方法中,我们使用正则表达式来找到所有数字的匹配项。之后,我们可以将字符串转换为数字并将其添加到sum变量中。

算法

  • Step 1 − Define the regex pattern.

  • Step 2 − Use the regex_search() method to find the match for the number string.

  • Step 3 − Make iterations using a while loop as long as we find matches.

  • Step 4 − In the while loop, use the stoi() method to convert the string to a number and add it to the sum variable.

  • 第5步 - 同样,使用match().suffix()方法更新字符串。这样我们就不会得到重复的匹配。

Example

#include <bits/stdc++.h>
using namespace std;
// Function to calculate the sum of the numbers found in the string
int getSumOfDigits(string str){
   // regex pattern to find the numbers in the string
   regex pattern("d+");
   smatch match;
   // variable to store the sum of the numbers
   int sum = 0;
   // using the regex_search() function to find the numbers
   while (regex_search(str, match, pattern)){
      // adding the numbers to the sum variable
      sum += stoi(match[0].str());
      // update the string
      str = match.suffix().str();
   }
   return sum;
}
int main(){
   // input alphanumeric string
   string str = "abc23@12";
   cout << "The sum of consecutive digits in the given string is - " << getSumOfDigits(str);
   return 0;
}

输出

The sum of consecutive digits in the given string is - 0
  • Time complexity − O(N), as regex finds matches by iterating through the string.

  • 空间复杂度 − O(1)

Conclusion

我们学习了三种不同的方法来找到字符串中连续数字的和。最后一种方法是最优化的代码,因为它使用了正则表达式。然而,对于初学者来说,使用正则表达式可能会很困难。

以上是给定一个字符串,求其中连续数字所组成的数的总和的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
C和XML:在项目中集成数据C和XML:在项目中集成数据May 10, 2025 am 12:18 AM

在C 项目中集成XML可以通过以下步骤实现:1)使用pugixml或TinyXML库解析和生成XML文件,2)选择DOM或SAX方法进行解析,3)处理嵌套节点和多级属性,4)使用调试技巧和最佳实践优化性能。

在C中使用XML:库和工具指南在C中使用XML:库和工具指南May 09, 2025 am 12:16 AM

在C 中使用XML是因为它提供了结构化数据的便捷方式,尤其在配置文件、数据存储和网络通信中不可或缺。1)选择合适的库,如TinyXML、pugixml、RapidXML,根据项目需求决定。2)了解XML解析和生成的两种方式:DOM适合频繁访问和修改,SAX适用于大文件或流数据。3)优化性能时,TinyXML适合小文件,pugixml在内存和速度上表现好,RapidXML处理大文件优异。

C#和C:探索不同的范例C#和C:探索不同的范例May 08, 2025 am 12:06 AM

C#和C 的主要区别在于内存管理、多态性实现和性能优化。1)C#使用垃圾回收器自动管理内存,C 则需要手动管理。2)C#通过接口和虚方法实现多态性,C 使用虚函数和纯虚函数。3)C#的性能优化依赖于结构体和并行编程,C 则通过内联函数和多线程实现。

C XML解析:技术和最佳实践C XML解析:技术和最佳实践May 07, 2025 am 12:06 AM

C 中解析XML数据可以使用DOM和SAX方法。1)DOM解析将XML加载到内存,适合小文件,但可能占用大量内存。2)SAX解析基于事件驱动,适用于大文件,但无法随机访问。选择合适的方法并优化代码可提高效率。

c在特定领域:探索其据点c在特定领域:探索其据点May 06, 2025 am 12:08 AM

C 在游戏开发、嵌入式系统、金融交易和科学计算等领域中的应用广泛,原因在于其高性能和灵活性。1)在游戏开发中,C 用于高效图形渲染和实时计算。2)嵌入式系统中,C 的内存管理和硬件控制能力使其成为首选。3)金融交易领域,C 的高性能满足实时计算需求。4)科学计算中,C 的高效算法实现和数据处理能力得到充分体现。

揭穿神话:C真的是一种死语吗?揭穿神话:C真的是一种死语吗?May 05, 2025 am 12:11 AM

C 没有死,反而在许多关键领域蓬勃发展:1)游戏开发,2)系统编程,3)高性能计算,4)浏览器和网络应用,C 依然是主流选择,展现了其强大的生命力和应用场景。

C#vs. C:编程语言的比较分析C#vs. C:编程语言的比较分析May 04, 2025 am 12:03 AM

C#和C 的主要区别在于语法、内存管理和性能:1)C#语法现代,支持lambda和LINQ,C 保留C特性并支持模板。2)C#自动内存管理,C 需要手动管理。3)C 性能优于C#,但C#性能也在优化中。

用C构建XML应用程序:实例用C构建XML应用程序:实例May 03, 2025 am 12:16 AM

在C 中处理XML数据可以使用TinyXML、Pugixml或libxml2库。1)解析XML文件:使用DOM或SAX方法,DOM适合小文件,SAX适合大文件。2)生成XML文件:将数据结构转换为XML格式并写入文件。通过这些步骤,可以有效地管理和操作XML数据。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具