hmz
hmz

Reputation: 1017

c++ char comparison to see if a string is fits our needs

i want to do my work if chars of the string variable tablolar does not contain any char but small letters between a-z and ','. what do you suggest?

if string tablolar is;

"tablo"->it is ok

"tablo,tablobir,tabloiki,tablouc"->it is ok

"ta"->it is ok

but if it is;

"tablo2"->not ok

"ta546465"->not ok

"Tablo"->not ok

"tablo,234,tablobir"->not ok

"tablo^%&!)=(,tablouc"-> not ok

what i tried was wrog;

    for(int z=0;z<tablolar.size();z++){
    if ((tablolar[z] == ',') || (tablolar[z] >= 'a' && tablolar[z] <= 'z'))
{//do your work here}}

Upvotes: 0

Views: 155

Answers (3)

dwMagician
dwMagician

Reputation: 1

The c function islower tests for lowercase. So you probably want something along these lines:

#include <algorithm>
#include <cctype> // for islower

bool fitsOurNeeds(std::string const& tabular)
{
    return std::all_of(tabular.begin(), tabular.end(),
        [](char ch)
    {
        return islower(ch) || ch == ',';
    });
}

Upvotes: 0

MSalters
MSalters

Reputation: 179819

tablolar.find_first_not_of("abcdefghijknmopqrstuvwxyz,") will return the position of the first invalid character, or std::string::npos if the string is OK.

Upvotes: 4

Detheroc
Detheroc

Reputation: 1921

bool fitsOurNeeds(const std::string &tablolar) {
    for (int z=0; z < tablolar.size(); z++)
        if (!((tablolar[z] == ',') || (tablolar[z] >= 'a' && tablolar[z] <= 'z')))
            return false;
    return true;
}

Upvotes: 0

Related Questions