繁体   English   中英

在字符串 C++ 中找到第一个没有零的数字

[英]Find first no zero number in a string C++

您好,有没有办法在字符串中找到第一个数字(从 1 到 9,没有零)? 有没有办法使用 std::find 或者我需要其他功能来做到这一点?

您可以使用 [] 运算符和 size() 函数将 std::string 作为字符数组遍历以获取其长度。 然后您可以检查从 49 到 57 的字符值(十进制,根据 ASCII 表)。

编辑

正如在下面的评论中所提到的,与从 '1' 到 '9' 的范围进行比较比从 49 到 57 的范围更清楚。但无论如何熟悉不同的字符表示法都是有用的。

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::string search_str = "abcd56";

    for (int i = 0; i < search_str.size(); ++i) {
        if (search_str[i] >= '1' && search_str[i] <= '9') {
            std::cout << "found at " << i << "\n";
            break;
        }
   }
}

至于 std::find,我最好使用 std::find_first_of,它需要两对迭代器,一个指向要搜索的范围,另一个指向要搜索的元素范围。 如果 std::find_first_of 的结果不等于搜索范围的 end(),则可以使用 std::distance(search_range.begin(), result) 找到第一个元素索引。

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::string search_str = "abcd56";
    std::vector<char> find_range {'1','2','3','4','5','6','7','8','9'};

    auto result = std::find_first_of(search_str.begin(), search_str.end(), find_range.begin(), find_range.end());

    if (result == search_str.end()) {
        std::cout << "no elements were found\n";
    } else {
        std::cout << "found match at "
                  << std::distance(search_str.begin(), result) << "\n";
    }
 }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM