0

0

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

王林

王林

发布时间:2023-08-28 09:17:14

|

849人浏览过

|

来源于tutorialspoint

转载

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

问题陈述

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 
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.

    Haiper
    Haiper

    一个感知模型驱动的AI视频生成和重绘工具,提供文字转视频、图片动画化、视频重绘等功能

    下载
  • 步骤 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 
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 
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

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

相关专题

更多
js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

508

2023.06.20

正则表达式不包含
正则表达式不包含

正则表达式,又称规则表达式,,是一种文本模式,包括普通字符和特殊字符,是计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串,通常被用来检索、替换那些符合某个模式的文本。php中文网给大家带来了有关正则表达式的相关教程以及文章,希望对大家能有所帮助。

247

2023.07.05

java正则表达式语法
java正则表达式语法

java正则表达式语法是一种模式匹配工具,它非常有用,可以在处理文本和字符串时快速地查找、替换、验证和提取特定的模式和数据。本专题提供java正则表达式语法的相关文章、下载和专题,供大家免费下载体验。

724

2023.07.05

java正则表达式匹配字符串
java正则表达式匹配字符串

在Java中,我们可以使用正则表达式来匹配字符串。本专题为大家带来java正则表达式匹配字符串的相关内容,帮助大家解决问题。

209

2023.08.11

正则表达式空格
正则表达式空格

正则表达式空格可以用“s”来表示,它是一个特殊的元字符,用于匹配任意空白字符,包括空格、制表符、换行符等。本专题为大家提供正则表达式相关的文章、下载、课程内容,供大家免费下载体验。

343

2023.08.31

Python爬虫获取数据的方法
Python爬虫获取数据的方法

Python爬虫可以通过请求库发送HTTP请求、解析库解析HTML、正则表达式提取数据,或使用数据抓取框架来获取数据。更多关于Python爬虫相关知识。详情阅读本专题下面的文章。php中文网欢迎大家前来学习。

293

2023.11.13

正则表达式空格如何表示
正则表达式空格如何表示

正则表达式空格可以用“s”来表示,它是一个特殊的元字符,用于匹配任意空白字符,包括空格、制表符、换行符等。想了解更多正则表达式空格怎么表示的内容,可以访问下面的文章。

229

2023.11.17

正则表达式中如何匹配数字
正则表达式中如何匹配数字

正则表达式中可以通过匹配单个数字、匹配多个数字、匹配固定长度的数字、匹配整数和小数、匹配负数和匹配科学计数法表示的数字的方法匹配数字。更多关于正则表达式的相关知识详情请看本专题下面的文章。php中文网欢迎大家前来学习。

526

2023.12.06

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
CSS3 教程
CSS3 教程

共18课时 | 4.1万人学习

PostgreSQL 教程
PostgreSQL 教程

共48课时 | 6.3万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号