c++ - 在字符串 C++ 中查找第一个不为零的数字
问题描述
您好,有没有办法在字符串中找到第一个数字(从 1 到 9,不为零)?有 std::find 的方法还是我需要其他功能来做到这一点?
解决方案
您好,有没有办法在字符串中找到第一个数字(从 1 到 9,不为零)?
您可以std::find_if
这样做:
template< class InputIt, class UnaryPredicate > InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
find_if 搜索谓词 p 返回 true 的元素
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
int main()
{
auto const str = std::string{"hello user #0002654"};
auto const first_non_zero_it = std::find_if(begin(str), end(str), [](char c) {
return std::isdigit(c) && c != '0';
});
std::cout << *first_non_zero_it << '\n'; // prints 2
}
推荐阅读
- javascript - 如何在卡片操作按钮组中使用对话框
- php - 自动加载转储后脚本因错误而终止
- postgresql - 在 Hasura 中跟踪 SQL 函数
- ag-grid - Ag-grid 动态隐藏 rowGroupPanel
- python - Python:将浮点数组元素更改为整数值,但python以浮点格式输出整数值
- sql-server - 无需截断或删除订阅者数据库表的事务复制设置
- docker - GCP docker 身份验证:使用 gcloud 如何比仅使用 JSON 密钥文件更安全?
- reactjs - 如何将 $el.text() 变成数字类型?
- jquery - Jquery 数据表 - 单击标题时如何进行多列排序和重绘表,它可以是 asc 或 desc
- android - 无法在 Android Studio 中打开项目