简体   繁体   中英

Find first no zero number in a string C++

Hello is there a way to find first number (from 1 to 9, no zero) in a string? Is there a way with std::find or do i need other function to do this?

You can traverse std::string as a char array with [] operator and size() function to get its length. Then you can check for char values from 49 to 57 (in decimal, according to ASCII table).

EDIT

As mentioned in the comments below, it would be clearer to compare with the range from '1' to '9' than from 49 to 57. But it would be useful anyway to get familiar with different char representations.

#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;
        }
   }
}

As for std::find, I would better use std::find_first_of, which takes two pairs of iterators, one pointing to the range to be searched in and another to the range of elements to search for. If the result of std::find_first_of is not equal to the end() of the searched range, then the first element index can be found with 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";
    }
 }

Hello is there a way to find first number (from 1 to 9, no zero) in a string?

You can use std::find_if to do so:

 template< class InputIt, class UnaryPredicate > InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );

find_if searches for an element for which predicate p returns 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
}

Demo: https://coliru.stacked-crooked.com/a/e3880961973ce038

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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