21xrx.com
2024-09-19 09:56:29 Thursday
登录
文章检索 我的文章 写文章
C++ 如何提取字符串中的数字?
2023-07-12 19:30:11 深夜i     --     --
C++ 提取 字符串 数字

在C++中,有时候需要从文本字符串中提取数字用于计算或比较。例如,从文件名中提取日期或从用户输入中提取数字等。本文将介绍几种常见的方法来提取字符串中的数字。

方法一:使用C++自带的字符串处理函数

C++提供了很多用于处理字符串的函数,其中有一些可以很方便地提取数字。这些函数包括`atoi`,`atof`和`sscanf`。`atoi`和`atof`函数都可以将字符串转换为整数或浮点数,而`sscanf`函数可以通过指定格式字符串来提取指定位置的数字。以下是使用这些函数的示例代码:


#include <cstdlib> // for atoi and atof

#include <cstdio> // for sscanf

int main()

{

  std::string str = "abc123def45.67xyz";

  const char* cstr = str.c_str();

  

  int num1 = atoi(cstr+3); // num1 = 123

  float num2 = atof(cstr+6); // num2 = 45.67

  

  int num3 = 0;

  float num4 = 0.0f;

  sscanf(cstr, "abc%ddef%fxyz", &num3, &num4); // num3 = 123, num4 = 45.67

  

  return 0;

}

方法二:使用正则表达式

正则表达式是一种强大的文本匹配工具,可以方便地从字符串中提取指定格式的内容。C++标准库中提供了` `头文件,可以使用该头文件内的正则表达式类来实现。以下是使用正则表达式提取数字的示例代码:


#include <regex>

#include <iostream>

#include <string>

int main()

{

  std::string str = "abc123def45.67xyz";

  

  std::regex reg("\\d+\\.?\\d*");

  std::smatch match;

  

  while (std::regex_search(str, match, reg))

  {

    std::cout << match[0] << std::endl; // 输出"123"和"45.67"

    str = match.suffix().str(); // 更新字符串,用于下一次匹配

  }

  

  return 0;

}

方法三:使用循环遍历

如果待提取数字的字符串格式比较特殊,上述方法可能不是很适用,此时可以使用循环遍历的方法。以下是使用循环遍历提取数字的示例代码:


#include <iostream>

#include <string>

int main()

{

  std::string str = "abc123def45.67xyz";

  std::string numStr = "";

  int num = 0;

  float decimal = 0.0f;

  bool isDecimal = false;

  for (char c : str)

  {

    if (isdigit(c))

    {

      numStr += c;

    }

    else if (c == '.' && !isDecimal)

    {

      isDecimal = true;

      numStr += c;

    }

    else if (numStr != "")

    {

      if (isDecimal)

      {

        decimal = std::stof(numStr);

      }

      else

      {

        num = std::stoi(numStr);

      }

      numStr = "";

      isDecimal = false;

    }

  }

  std::cout << "num = " << num << ", decimal = " << decimal << std::endl; // 输出"num = 123, decimal = 45.67"

  return 0;

}

总结

本文介绍了几种常见的从字符串中提取数字的方法,包括使用C++自带的字符串处理函数,使用正则表达式以及使用循环遍历等。需要根据实际需求选择适合的方法,以提高效率和准确度。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复