From: Mikko Rasa Date: Wed, 24 Dec 2008 07:08:10 +0000 (+0000) Subject: Add utility functions to check the contents of a string X-Git-Tag: strings-1.1~8 X-Git-Url: http://git.tdb.fi/?a=commitdiff_plain;h=f9e0275e476540c1b5d61c03a6a87d521856059b;p=libs%2Fcore.git Add utility functions to check the contents of a string Fix str_to_bool --- diff --git a/source/lexicalcast.cpp b/source/lexicalcast.cpp index 687a37b..cdd5578 100644 --- a/source/lexicalcast.cpp +++ b/source/lexicalcast.cpp @@ -211,10 +211,14 @@ string bool_to_str(bool b, const Fmt &f) bool str_to_bool(const string &s) { + if(s.empty()) + throw LexicalError("Empty input in boolean conversion"); + if(s=="1" || s=="true" || s=="yes" || s=="on") return true; else if(s=="0" || s=="false" || s=="no" || s=="off") - return true; + return false; + throw LexicalError("Invalid input in boolean conversion"); } diff --git a/source/utils.cpp b/source/utils.cpp index d67cc7e..baf1333 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -1,7 +1,7 @@ /* $Id$ This file is part of libmspstrings -Copyright © 2006-2007 Mikko Rasa +Copyright © 2006-2008 Mikko Rasa Distributed under the LGPL */ @@ -46,6 +46,14 @@ vector do_split(const string &str, const string &sep, int max_split) return result; } +bool check_str(const std::string &str, int (*pred)(int)) +{ + for(string::const_iterator i=str.begin(); i!=str.end(); ++i) + if(!pred(*i)) + return false; + return true; +} + } namespace Msp { @@ -79,6 +87,21 @@ string toupper(const string &str) return result; } +bool isnumrc(const string &str) +{ + return check_str(str, isdigit); +} + +bool isalpha(const string &str) +{ + return check_str(str, isalpha); +} + +bool isalnum(const string &str) +{ + return check_str(str, isalnum); +} + vector split(const string &str, const string &sep, int max_split) { return do_split(str, sep, max_split); diff --git a/source/utils.h b/source/utils.h index 5492f95..44c2edb 100644 --- a/source/utils.h +++ b/source/utils.h @@ -1,7 +1,7 @@ /* $Id$ This file is part of libmspstrings -Copyright © 2006-2007 Mikko Rasa +Copyright © 2006-2008 Mikko Rasa Distributed under the LGPL */ @@ -33,6 +33,28 @@ Converts a string to upper case. */ std::string toupper(const std::string &); +/** +Checks whether a string consists of digits only. +*/ +bool isnumrc(const std::string &); + +/** +Checks whether a string consists of alphabetic characters only. +*/ +bool isalpha(const std::string &); + +/** +Checks whether a string consists of alphanumeric characters only. +*/ +bool isalnum(const std::string &); + +/* These are required to make the standard version work from inside the Msp +namespace */ +using std::tolower; +using std::toupper; +using std::isalpha; +using std::isalnum; + /** Splits a string at occurrences of any of the characters in sep. If max_split is non-negative, at most that many split will be performed, i.e. the resulting