Neal
Neal

Reputation: 19

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?

Upvotes: 0

Views: 1454

Answers (2)

Bord81
Bord81

Reputation: 555

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

Upvotes: 1

YSC
YSC

Reputation: 40060

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

Upvotes: 2

Related Questions