haierophanto
haierophanto

Reputation: 51

How to find a word which contains digits in a string

I need to check words inside the string to see whether any of them contains digits, and if it isn't — erase this word. Then print out the modified string

Here's my strugle to resolve the problem, but it doesn't work as I need it to

void sentence_without_latin_character( std::string &s ) {
    std::cout << std::endl;

    std::istringstream is (s);
    std::string word;
    std::vector<std::string> words_with_other_characters;

    while (is >> word) {
        std::string::size_type temp_size = word.find(std::ctype_base::digit);
        if  (temp_size == std::string::npos) {
            word.erase(word.begin(), word.begin() + temp_size);
        }
        words_with_other_characters.push_back(word);
    }

    for (const auto i: words_with_other_characters) {
        std::cout << i << " ";
    }

    std::cout << std::endl;
}

Upvotes: 2

Views: 191

Answers (2)

David G
David G

Reputation: 96800

As Acorn explained, word.find(std::ctype_base::digit) does not search for the first digit. std::ctype_base::digit is a constant that indicates a digit to specific std::ctype methods. In fact there's a std::ctype method called scan_is that you can use for this purpose.

void sentence_without_latin_character( std::string &s ) {
  std::istringstream is (s);
  std::string word;

  s.clear();
  auto& ctype = std::use_facet<std::ctype<char>>(std::locale("en_US.utf8"));
  while (is >> word) {
    auto p = ctype.scan_is(std::ctype_base::digit, word.data(), &word.back()+1);
    if (p == &word.back()+1) {
      s += word;
      if (is.peek() == ' ') s += ' ';
    }
  }

  std::cout << s << std::endl;
}

Upvotes: 0

Acorn
Acorn

Reputation: 26066

This part is not doing what you think it does:

word.find(std::ctype_base::digit);

std::string::find only searches for complete substrings (or single characters).

If you want to search for a set of some characters in a string, use std::string::find_first_of instead.

Another option is testing each character using something like std::isdigit, possibly with an algorithm like std::any_of or with a simple loop.

Upvotes: 2

Related Questions