Click here to Skip to main content
Click here to Skip to main content
 
Add your own
alternative version

XMLLib for PUGXML with XPath

, 29 Oct 2009
A library for PugXML which implements XPath
//**************************************************************************************************************************
//* Blue - General Purpose C++ Library
//* Copyright (c) 2002 Josh Harler
//*
//* This software is provided 'as-is', without any express or implied warranty. In no event
//* will the authors be held liable for any damages arising from the use of this software.
//*
//* Permission is granted to anyone to use this software for any purpose, including commercial
//* applications, and to alter it and redistribute it freely, subject to the following restrictions:
//*
//* 	1. The origin of this software must not be misrepresented; you must not claim that you
//* 	wrote the original software. If you use this software in a product, an acknowledgment in the
//* 	product documentation would be appreciated but is not required.
//*
//* 	2. Altered source versions must be plainly marked as such, and must not be misrepresented as
//* 	being the original software.
//*
//* 	3. This notice may not be removed or altered from any source distribution.
//*
//*
//* file   Common/BString.h
//**

#ifndef __blue_common_BString_h_included__
#define __blue_common_BString_h_included__

// Public Headers ==========================================================================================================

// Public Defines/Enums/Typedefs/Etc. ======================================================================================

#if !defined(BLUE_EXPORT)
#	define BLUE_EXPORT
#endif


// Public Classes/Structs ==================================================================================================

namespace blue
{
    namespace common
    {
        // ===============================================================
        //  Class BString (Normal, Pass by value)
        //  Note: Changed from String to BString to avoid name conflicts
        // ===============================================================
        
        /**
        * \class BString
        * \brief %BString manipulating class.
        * \ingroup Common
        *
        * There's not much to say about this class.  It exists to allow
        * for very easy string manipulation and querying.
        *
        * One important thing to keep in mind is that any manipulation
        * function returns a new string.  The following code:
        *
        * \code
        * BString myBString("abcdefg");
        * myBString.toUpper();
        * \endcode
        *
        * Does not do what you might think.  The toUpper() function
        * returns a new %BString instance as the result of the function.
        * Therefore, myBString has not been changed.  In order to perform
        * this operation on the myBString variable, you must do this:
        *
        * \code
        * BString myBString("abcdefg");
        * myBString = myBString.toUpper();
        * \endcode
        */
        class BString
        {
        public:
        /**
        * Determines what the string should do when constructing with
        * a c - style string.
            */
            enum create_e
            {
                NORMAL, //!< treat it normally, create a copy of the string
                STATIC, //!< treat it as a static, unchanging string - just point to it (no memory is allocated)
            };
            
            // ===========================================================
            //  creation/destruction
            // ===========================================================
            
            /** Constructor. */
            BString();
            /** Copy constructor. */
            BString(const BString& str);
            /** C - Style string constructor. */
            BString(const char* str, create_e create = NORMAL);
            /**
            * C - Style string constructor, limited by length rather than
            * the null terminator.
            *
            * \param str The c - style string to copy
            * \param len The number of characters to use in the string.
            */
            BString(const char* str, int len, create_e create = NORMAL);
            /** Cast constructor.  Casts the character to a string. */
            BString(char ch);
            /** Cast constructor.  Casts the number to a string. */
            explicit BString(int num);
            /** Cast constructor.  Casts the number to a string. */
            explicit BString(float num);
            /** Cast constructor.  Casts the number to a string. */
            explicit BString(double num);
            /** Cast constructor.  Casts the number to a string. */
            explicit BString(unsigned int num);
            
            /** Destructor. */
            ~BString();
            
            // ===========================================================
            //  searching
            // ===========================================================
            
            enum
            {
                npos = -1,	//!< The location does not exist.
            };
            
            /**
            * Finds the position of the given string if this string
            * contains it or BString::npos if the string cannot be found.
            */
            int findPos(const char* search, int start = npos) const;
            /** overload */
            int findPos(const BString& search, int start = npos) const;
            
            /**
            * Identical to BString::findPos, except that case is not taken into
            * account when searching the string.
            */
            int findPosIgnoreCase(const char* search, int start = npos) const;
            /** overload */
            int findPosIgnoreCase(const BString& search, int start = npos) const;
            
            /**
            * Similiar to BString::findPos, but searches the string backwards
            * when looking for the position of the string.
            */
            int findPosR(const char* search, int start = npos) const;
            /** overload */
            int findPosR(const BString& search, int start = npos) const;
            
            /**
            * Identical to BString::findPosR, except that case is not taken into
            * account when searching the string.
            */
            int findPosRIgnoreCase(const char* search, int start = npos) const;
            /** overload */
            int findPosRIgnoreCase(const BString& search, int start = npos) const;
            
            /**
            * Counts the number of times the given string occurs in this
            * string.
            */
            int count(const char* search) const;
            /** overload */
            int count(const BString& search) const;
            
            /**
            * Identical to BString::count, except that case is not taken into
            * acount when searching the string.
            */
            int countIgnoreCase(const char* search) const;
            /** overload */
            int countIgnoreCase(const BString& search) const;
            
            /** Returns the length of the string. */
            int getLength() const;
            
            // ===========================================================
            //  equality
            // ===========================================================
            
            /**
            * Should be used when testing for empty strings(or use
            * BString::isEmpty()) and when assigning empty strings(rather
            * than using "").
            */
            static const BString null;
            
            
            /** Determines if the two strings are equal. */
            bool equals(const char* str) const;
            /** overload */
            bool equals(const BString& str) const;
            
            /**
            * Identical to BString::equals, except that case is not taken into
            * account when comparing the string.
            */
            bool equalsIgnoreCase(const char* str) const;
            /** overload */
            bool equalsIgnoreCase(const BString& str) const;
            
            /**
            * Determines if this string matches the given wildcard.
            *
            * This isn't a regular expression matcher.  The only special
            * characters that are used are '?' and '*'.
            */
            bool equalsWildCard(const char* str) const;
            /** overload */
            bool equalsWildCard(const BString& str) const;
            /**
            * Identical to equalsWildCard, except that case is not taken into
            * account when comparing the string.
            */
            bool equalsWildCardIgnoreCase(const char* str) const;
            /** overload */
            bool equalsWildCardIgnoreCase(const BString& str) const;
            
            /**
            * Determines if the first part of this string matches the
            * given string.
            */
            bool beginsWith(const char* str) const;
            /** overload */
            bool beginsWith(const BString& str) const;
            /**
            * Identical to beginsWith, except that case is not taken into
            * account when comparing the string.
            */
            bool beginsWithIgnoreCase(const char* str) const;
            /** overload */
            bool beginsWithIgnoreCase(const BString& str) const;
            
            /**
            * Determines if the last part of this string matches the
            * given string.
            */
            bool endsWith(const char* str) const;
            /** overload */
            bool endsWith(const BString& str) const;
            /**
            * Identical to endsWith, except that case is not taken into
            * account when comparing the string.
            */
            bool endsWithIgnoreCase(const char* str) const;
            /** overload */
            bool endsWithIgnoreCase(const BString& str) const;
            
            /**
            * Compares the two strings the same way the c function strcmp does.
            */
            int  compare(const char* str) const;
            /** overload */
            int  compare(const BString& str) const;
            /**
            * Identical to BString::compare, except that case is not taken into
            * account when comparing the string.
            */
            int  compareIgnoreCase(const char* str) const;
            /** overload */
            int  compareIgnoreCase(const BString& str) const;
            
            /** Determines if the string contains any data */
            bool isEmpty() const;
            
            // ===========================================================
            //  manipulation
            // ===========================================================
            
            /**
            * Creates a new string with the given string inserted into the
            * text of this string at the given position.
            */
            BString insert(const char* str, int before) const;
            /** overload */
            BString insert(const BString& str, int before) const;
            
            /**
            * Creates a new string of this string's text with the given
            * section removed.
            */
            BString remove(int start, int chars) const;
            
            /**
            * Creates a new string of this string's text with all instances
            * of the given string removed.
            */
            BString removeAll(const char* str) const;
            /** overload */
            BString removeAll(const BString& str) const;
            
            /**
            * Identical to BString::removeAll, except that case is not taken
            * into account when searching the string.
            */
            BString removeAllIgnoreCase(const char* str) const;
            /** overload */
            BString removeAllIgnoreCase(const BString& str) const;
            
            /**
            * Creates a new string of this string's text with all instances
            * of the given string replaced with the other given string.
            */
            BString replaceAll(const char* str, const char* with) const;
            /** overload */
            BString replaceAll(const BString& str, const BString& with) const;
            
            /**
            * Identical to BString::replaceAll, except that case is not taken
            * into account when searching the string.
            */
            BString replaceAllIgnoreCase(const char* str, const char* with) const;
            /** overload */
            BString replaceAllIgnoreCase(const BString& str, const BString& with) const;
            
            /**
            * Creates a new string using printf style formating.
            */
            static BString format(const char* str, ...);
            /** overload */
            static BString format(const BString& str, ...);
            /**
            * Overloaded to accept a maximum buffer size.  The reason for this is
            * that the default buffer size is rather small and attempting to write
            * a large amount of data to a small buffer will result in the data
            * being cut off.  This function allows you to set the buffer size
            * so that this will not happen.
            */
            static BString format(int maxSize, const char* str, ...);
            /** overload */
            static BString format(int maxSize, const BString& str, ...);
            
            /**
            * Creates a new string with the given length and filled with the
            * given character.
            */
            static BString fill(int len, char ch);
            
            /**
            * Trims all whitespace from the beginning and end of the string.
            */
            BString trim() const;
            /** Trims all whitespace from the beginning of the string. */
            BString trimLeft() const;
            /** Trims all whitespace from the end of the string. */
            BString trimRight() const;
            
            /**
            * If the string isn't at least the given length, the string
            * is padded at it's front with the given character until the
            * given length is reached.
            */
            BString padLeft(int len, char ch) const;
            /**
            * Identical to BString::padLeft, except the padding occurs at
            * the end of the string.
            */
            BString padRight(int len, char ch) const;
            
            /**
            * Replaces the smallest index in the string with the given string.
            * For example:
            * \code
            * BString msg("Testing, {3}, {2}, {1}");
            * BString newMsg = msg.arg("three").arg("two").arg("one");
            * \endcode
            *
            * Will result in the string:
            * \code
            * newMsg == "Testing, one, two, three"
            * \endcode
            */
            BString arg(const char* arg) const;
            /** overload */
            BString arg(BString arg) const;
            
            /**
            * Returns a string that contains the same text of this one,
            * except that no other strings will be referencing the same
            * memory.
            * This function should always be called before a call to
            * BString::getAsCStr() is used to pass the c - style pointer to
            * a function expecting a null terminated string.
            */
            BString makeUnique() const;
            
            // ===========================================================
            //  disection
            // ===========================================================
            
            /**
            * Returns a string containing the first given number of
            * characters from this string.
            */
            BString left(int chars) const;
            /**
            * Returns a string containing the last given number of
            * characters from this string.
            */
            BString right(int chars) const;
            /**
            * Returns a string containing the text located at the
            * given index and including the given number of characters.
            */
            BString subString(int start, int chars = npos) const;
            
            /**
            * Returns a string containing the text of this one except
            * for the leftmost given characters.
            */
            BString stripFromLeft(int characters) const;
            /**
            * Returns a string containing the text of this one except
            * for the rightmost given characters.
            */
            BString stripFromRight(int characters) const;
            
            /** Returns a string containing the text of this one in reverse order. */
            BString reverse() const;
            
            /** Returns a string containing the text of this one in upper case letters. */
            BString toUpper() const;
            /** Returns a string containing the text of this one in lower case letters. */
            BString toLower() const;
            
            // ===========================================================
            //  conversion
            // ===========================================================
            
            /** Determines if the string is a valid integer */
            bool isValidInt(int base = 10) const;
            
            /** Determines if the string is a valid float */
            bool isValidFloat() const;
            
            /** Determines if the string is a valid double */
            bool isValidDouble() const;
            
            /**
            * Returns the text of the string cast to an integer, or 0 if
            * the string is not a valid int.
            */
            int getAsInt(int base = 10) const;
            /**
            * Returns the text of the string cast to a float, or 0.0f if
            * the string is not a valid float.
            */
            float getAsFloat() const;
            /**
            * Returns the text of the string cast to a double, or 0.0 if
            * the string is not a valid double.
            */
            double getAsDouble() const;
            /**
            * Returns the text of the string cast to a c - style string.
            */
            const char* getAsCStr() const;
            
            /**
            * Accesses the character at the given index.  No checks are
            * made to validate the index and the access is read only
            *(the character cannot be changed)
            */
            const char& operator[](int index) const;	// read only
            
            // assignment/appending operators
            BString& operator=(const char* str);
            BString& operator=(const BString& str);
            BString  operator+(const char* str);
            BString  operator+(const BString& str);
            BString& operator+=(const char* str);
            BString& operator+=(const BString& str);
            
            // equality operators
            bool operator==(const char* str) const { return (compare(str) == 0); }
            bool operator==(const BString& str) const { return (compare(str) == 0); }
            bool operator!=(const char* str) const { return (compare(str) != 0); }
            bool operator!=(const BString& str) const { return (compare(str) != 0); }
            bool operator < (const char* str) const { return (compare(str) <  0); }
            bool operator < (const BString& str) const { return (compare(str) <  0); }
            bool operator <=(const char* str) const { return (compare(str) <= 0); }
            bool operator <=(const BString& str) const { return (compare(str) <= 0); }
            bool operator>(const char* str) const { return (compare(str) >  0); }
            bool operator>(const BString& str) const { return (compare(str) >  0); }
            bool operator>=(const char* str) const { return (compare(str) >= 0); }
            bool operator>=(const BString& str) const { return (compare(str) >= 0); }
    private:
        BString(char* str, bool own);
        
        void refInc();
        void refDec();
        void refCreate(int len);
        void refCreate(const BString& str);
        void refCreate(const char* str, bool own);
        
        int*  m_refCnt; // The number of strings referencing this buffer
        char* m_refBuf; // The shared character string
        int*  m_refLen; // The length of the character string
        
        const char* m_start;  // The start of this string
        int         m_len;    // the length of this string
    };
}
}	// namespaces


// Public External Variables ===============================================================================================

// Public Function Prototypes ==============================================================================================

namespace blue
{
    namespace common
    {
        template <typename type>
            BString operator+(const type& var, const BString& str)
        {
            BString val(var);
            return (val + str);
        }
    }
}	// namespaces


// Public Inline Functions =================================================================================================

#endif // include guard

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

JCrane2
Web Developer
United States United States
No Biography provided

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 29 Oct 2009
Article Copyright 2003 by JCrane2
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid