Shijury
Shijury

Reputation: 39

How to check a String for special characters?

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?

Upvotes: 0

Views: 327

Answers (1)

smac89
smac89

Reputation: 43206

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;

Upvotes: 0

Related Questions