Reputation: 207
I need to do 2 basic functions in c++
bool validMeno(const string& text){
if ()
return DUMMY_BOOL;
}
bool validPriezvisko(const string& text){
return DUMMY_BOOL;
}
first one returns true if the input is string with first letter uppercase second one is true when all string is uppercase plese help me i am noob in c++
Upvotes: 0
Views: 300
Reputation: 7603
Use header cctype and this should work.
bool validMeno(const string& text){
if (text.size() == 0)
return false;
return isupper(text[0]);
}
bool validPriezvisko(const string& text){
if (text.size() == 0)
return false;
for (std::string::size_type i=0; i<text.size(); ++i)
{
if (islower(text[i]))
return false;
}
return true;
}
EDIT:
Since you also want to check for strings that only stores alphabetic characters, you can use isalpha
from cctype
to check for that.
Upvotes: 1
Reputation: 100718
Your problem is not completely specified. Should non-alpha characters be treated as lower-case or upper case? If they should be considered uppercase you could use:
#include <string>
#include <algorithm>
using namespace std;
bool validMeno(const string& text) {
return !text.empty() && isupper(text[0]);
}
bool validPriezvisko(const string& text) {
return !any_of(begin(text), end(text), islower);
}
On the other hand if non-alpha characters should be considered lower-case:
#include <string>
#include <algorithm>
using namespace std;
bool validMeno(const string& text) {
return !text.empty() && !islower(text[0]);
}
bool validPriezvisko(const string& text) {
return all_of(begin(text), end(text), isupper);
}
Upvotes: 0
Reputation: 4314
The relational operator ==
is defined for the C++ class std::string
. The best touppercase implementation seems to come from the Boost String Algorithms library (see here), so I'll use that in my example. Something like this should work:
#include <boost/algorithm/string.hpp>
#include <string>
bool first_n_upper(const std::string & text, size_t n)
{
if (text.empty())
return false;
std::string upper = boost::to_upper_copy(text);
return text.substr(0, n) == upper.substr(0, n);
}
bool validMeno(const std::string & text)
{
return first_n_upper(text, 1);
}
bool validPriezvisko(const std::string & text)
{
return first_n_upper(text, std::string::npos);
}
Upvotes: 0