首页 > 解决方案 > 在字符串 C++ 中查找第一个不为零的数字

问题描述

您好,有没有办法在字符串中找到第一个数字(从 1 到 9,不为零)?有 std::find 的方法还是我需要其他功能来做到这一点?

标签: c++stringnumbers

解决方案


您好,有没有办法在字符串中找到第一个数字(从 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
}

演示:https ://coliru.stacked-crooked.com/a/e3880961973ce038


推荐阅读