21xrx.com
2025-03-23 18:25:07 Sunday
文章检索 我的文章 写文章
C++如何提取字符串中的数字
2023-06-22 01:24:43 深夜i     --     --
C++ 提取 字符串 数字

C++是一种广泛应用于计算机程序设计的高级编程语言,经常用来处理字符串。然而,在处理字符串的过程中,有时会出现需要提取字符串中的数字的需求,本文将介绍如何使用C++提取字符串中的数字。

首先,需要明确的是,字符串中的数字可能会以多种形式出现,包括整数、浮点数、负数等。因此,在提取字符串中的数字之前,需要先判断字符串中是否包含数字。可以使用以下代码进行判断:

#include <string>
#include <cctype>
bool has_numeric(const std::string& str) {
  for (char c : str) {
    if (std::isdigit(c))
      return true;
    
  }
  return false;
}

上述代码使用了C++标准库中的string和ctype头文件,通过逐个检查字符串中的字符是否为数字字符,来确定字符串中是否包含数字。如果包含数字,就可以开始提取数字了。

接下来,需要确定提取数字的方式。一种常见的方式是使用正则表达式。C++中可以使用regex头文件实现正则表达式的功能。例如,以下代码使用正则表达式匹配字符串中的数字,并存储到一个vector中:

#include <string>
#include <regex>
#include <vector>
std::vector<std::string> extract_numeric(const std::string& str) {
  std::vector<std::string> results;
  std::regex pattern("[+-]?[0-9]+(\\.[0-9]+)?");
  std::smatch match;
  std::string::const_iterator search_start(str.cbegin());
  while (std::regex_search(search_start, str.cend(), match, pattern)) {
    results.push_back(match[0]);
    search_start = match.suffix().first;
  }
  return results;
}

上述代码中,首先定义了一个正则表达式的pattern,用于匹配数字字符串。这个正则表达式可以匹配整数、带小数点的浮点数,以及带有正负号的数字。然后使用regex_search函数匹配字符串中的数字,并将结果存储到vector中。

当然,除了使用正则表达式,还可以使用循环逐个检查字符串中的字符,来提取数字。以下是一种基本的实现方式:

#include <string>
#include <vector>
#include <cctype>
std::vector<std::string> extract_numeric(const std::string& str) {
  std::string current;
  std::vector<std::string> results;
  for (char c : str) {
    if (std::isdigit(c) || c == '.' || c == '-' || c == '+') {
      current += c;
    } else {
      if (!current.empty()) {
        results.push_back(current);
        current.clear();
      }
    }
  }
  if (!current.empty()) {
    results.push_back(current);
  }
  return results;
}

这个实现方式首先定义了一个current字符串,用于保存当前正在提取的数字。然后逐个检查字符串中的字符,如果是数字、小数点、正负号,则将它们添加到current中,直到遇到非数字字符或字符串结束。如果当前正在提取的数字不为空,则将它保存到结果vector中,并清空current。最后,如果current中还有数字,则将它也保存到结果vector中。

总之,提取字符串中的数字可以使用正则表达式或循环遍历字符串的方式来实现。使用C++标准库中的string和regex头文件可以轻松地实现这个功能,希望本文对你有所帮助。

  
  

评论区