#ifndef STRINGUTIL_H // -*- c++ -*- #define STRINGUTIL_H /// // Copyright (C) 2002 - 2004, Fredrik Arnerup & Rasmus Kaj, See COPYING /// #include "typeinfo.h" #include #include #include #include // The to / from string converters here is declared inline, since that is a // lot easier than actually makeing partial template compilation work as it // should. /** * Convert a string to an arbitrary type. * \param C the type to convert to. * \param value the value to convert. */ template C to(const std::string &value) { std::istringstream s(value); C c; if(s >> c) { if(!s.eof() && s.peek() != EOF) throw std::runtime_error("Trailing junk in " + TypeInfo::name() + " \"" + value + '"'); return c; } else throw std::runtime_error("Bad " + TypeInfo::name() + " value: \"" + value + '"'); } /** Specialization; a string is "converted" to itself without change. */ template<> inline std::string to(const std::string& value) { return value; } /** * Convert a value of an arbitrary type to its string representation. * \param C the type of value (can be implicit). * \param c the actual value */ template std::string tostr(const C& c) { std::ostringstream s; s << c; // std::ends inserts a null character _inside_ the string // this can lead to subtle errors return s.str(); } template<> bool to(const std::string& value); template<> std::string tostr(const bool& b); /** * Check if a character is whitespace. */ bool whitespace(char c); /** * Remove whitespace at the beginning and / or end of a string. * \param s the string * \param front if true, remove whitespace at the beginning of s. * \param back if true, remove whitespace at the end of s. */ std::string strip_whitespace(std::string s, bool front=true, bool back=true); /** * Check if a specific string starts with a given string. * \param str the (longer) string to look in. * \param start the string to look for. */ bool starts_with(const std::string& str, const std::string& start); /** * Check if a specific string starts with a given character. * \param str the string to look in. * \param start the character to look for. */ inline bool starts_with(const std::string& str, char start) { return str.length() > 0 && str[0] == start; } /** * A substitute for getline that treats line breaks in a * platform-independant way */ std::istream &safe_getline(std::istream &in, std::string &line); /** * Escape characters that are illegal in xml. */ std::string to_xml(const std::string str); /** * Convert a number to roman numerals. * Will throw an exception if the number is outside the range 1 - 3999. */ std::string to_roman(int num); #endif