0

I'm working on a problem in C++ and here's my question: I get a string from an object and I want to detect if there is a character that is not alphanumeric or a special character like /, (, $ and so on. I cannot imagine of a way other than asking

if (Text.Pos("A") > 0)

if (Text.Pos("B") > 0)

.....

Is there a standard way/method to do this quicker?

smac89
  • 39,374
  • 15
  • 132
  • 179
Shijury
  • 39
  • 3
  • If you were using `std::string` then you could use its [`find_first_not_of()`](https://en.cppreference.com/w/cpp/string/basic_string/find_first_not_of) method. But you clearly are not using `std::string`, so you will have to see if your chosen string class (which is it exactly?) has a ready-made function to do similar. If not, you will have to loop through the string manually testing each character until you find one that matches your criteria. – Remy Lebeau Jan 17 '19 at 07:34
  • 1
    please provide a [mcve] – Alan Birtles Jan 17 '19 at 08:05

1 Answers1

0

I'm assuming your proposed solution is to check if all the alphanumeric characters are inside the string. This method won't work because you have to also take into account the length of the string because it is possible to get a string that contains all the alphanumeric characters plus one special character.

Short of nesting thousands of if-statements to also detect non alphanumeric characters, this is a solution that works:

(I am assuming that Text can be iterated over, using range-based for-loops)

You can use std::find_if

#include <algorithm>
#include <iterator>
#include <cctype>
#include <iostream>

auto it = std::find_if(std::begin(Text), std::end(Text), [](const char c) {
    return std::isalnum(c) == 0; // Not alphanumeric
});

if (it == std::end(Text)) {
    std::cout << "Text is fine!";

} else {
    std::cout << "Text contains non-alphanumeric character: '" << *it << "'";
}

std::cout << std::endl;
smac89
  • 39,374
  • 15
  • 132
  • 179
  • This only works if the type of `Text` has an iterator that provides access to the individual characters. And even then, the question asks for "not alphanumeric **or a special character**". – Pete Becker Jan 17 '19 at 16:36
  • @PeteBecker, good point on the iterator. OP can disambiguate that part as he sees fit. The point is to iterate over the contents of the 'string'. "`...or a special character like /, (, $`". Special characters are not alphanumeric, so I left it at just checking for non alphanumeric – smac89 Jan 17 '19 at 19:10