if you use char* as a string, then you can compare and assign individual characters using the == sign.
char* s1 = "I am a string";
// Now, copy this into s2.....
// note that the following does NOT
// verify that s1 is not null
// which could cause a problem.
char* s2 = new char[strlen(s1) + 1];
strcpy(s2, s1); // I did NOT verify parameter order...
Consider a safe string length function:
// This will return zero for the length
// rather than having a null pointer exception.
int safe_strlen(const char* c)
{
return (c != null) ? strlen(c) : 0;
}
Okay, now I will treat a null pointer the same as an empty string...
char* clone_string(const char* c)
{
char* new_c = new char[safe_strlen(c)+1];
if (c != null)
strcpy(new_c, c);
else
new_c[0] = 0;
return new_c;
}
Remember, when you say
char* s1 = "hello";
s1 is really just acting as a pointer to some memory that contains the characters "hello" followed by a 0. If you now have
char* s2 = s1;
Then s2 points to the same memory as s1. You must, therefore, use strcpy to copy the characters into s2, but first you must have memory allocated for use. In case it is instructive, here is my own implementation of a string class in C++. Note that I use strcpy and a few other string methods.
++++++++++++++++++++++++++
#ifndef ADPString_hpp
#define ADPString_hpp
// #define TestADPString
//************************
//** **
//** Copyright 1996-2002 by Andrew D. Pitonyak **
//** **
//** This code is free for personal use. Use for profit requires prior **
//** permission. I appreciate bug reports and fixes. **
//** **
//** Andrew D. Pitonyak **
//** 4446 Mobile Drive #105 **
//** Columbus, OH 43220 **
//** code@pitonyak.org **
//** **
//************************
//** **
//** This contains a simple string class. It is kind of wasteful given **
//** that a few extra pieces such as length is stored for each and every **
//** string and given that each string stores the case sensitivity **
//** **
//** **
//** April 28, 1998 **
//** Added "append" versions of I/O functions and changed the read **
//** functions to clear the string first. Also changed unsigned long **
//** variables to use unsigned int. **
//** **
//** May 8, 1998 **
//** Added the shiftDown() function **
//** **
//** March 10, 2002 **
//** The code would not even compile. There were many errors. **
//** I have no idea what I did or when, but this is clearly a **
//** modified copy of the original. I probably added functions **
//** also present in RogueWave. **
//** **
//** I changed all unsigned ints to just int. **
//** **
//** April 2, 2002 **
//** Added new methods like fnMatch(), startsWith(), endsWith() **
//** countChar(). Added streaming operators and append() to more **
//** easily add more types into a string. Added limited support **
//** to create an ADPString from an std::string **
//** **
//************************
#include "myconfig.hpp"
#include <iostream.h>
#include <string>
class ADPString {
public:
ADPString(const char* aString=0, int isCase = 0, int num = -1);
ADPString(const ADPString& aString, int isCase = 0, int num = -1);
ADPString(const std::string& aString, int isCase = 0, int num = -1);
ADPString(char c, int isCase = 0, int num = -1);
~ADPString();
const char* c_str() const {return _data;}
int length() const {return _length;}
void caseSensitive(int isCase) {_caseSensitive = isCase;}
int caseSensitive() const {return _caseSensitive;}
void to_upper() {toUpper();}
void to_lower() {toLower();}
void toUpper();
void toLower();
const ADPString& operator=(const ADPString& aString);
const char* operator=(const char* aString);
char operator=(char c);
int operator==(const ADPString& aString) const;
int operator!=(const ADPString& aString) const;
int operator< (const ADPString& aString) const;
int operator> (const ADPString& aString) const;
int operator<=(const ADPString& aString) const;
int operator>=(const ADPString& aString) const;
int cmp(const ADPString& aString) const;
int cmp(const char* aString) const;
int endsWith(const char* str) const;
int endsWith(char c) const;
int endsWith(const ADPString& str) const;
int startsWith(const char* str) const;
int startsWith(char c) const;
int startsWith(const ADPString& str) const;
int countChar(char c) const;
void operator+=(const std::string& aString);
void operator+=(const ADPString& aString);
void operator+=(const char* aString);
void operator+=(char aChar);
char& operator[](int pos);
char operator[](int pos) const;
//
// ?? if you create regular expressions, then add an
// operator to do the following operator with regular
// expressions as well
//
char& operator()(int pos) {return operator[](pos);}
char operator()(int pos) const {return operator[](pos);}
//
// Chop, indicate how long the string will be.
//
void truncate(int pos);
void resize(int pos) {truncate(pos);}
void grow(int pos, int copyString=1);
// Move pos to 0
void shiftDown(int pos);
//
// Find a character
//
int findFirst(int c) const;
int findLast(int c) const;
//
// Remove spaces
//
void trimEnd();
void trimFront();
void trimAll() {trimEnd(); trimFront();}
//
// This extra is allocated every time
//
int extra() const {return _extra;}
void extra(int aVal) {_extra = aVal;}
//
// When there is this much extra space, then reallocate
// Be certain that _cleanup > _extra
//
int cleanup() const {return _cleanup;}
void cleanup(int aVal){ _cleanup = aVal;}
void doCleanup();
int lastCharIs(char aChar) const {return endsWith(aChar);}
void forceLastChar(char aChar);
istream& readToDelimiter(istream& aStream, char aDelimiter);
istream& readAToken(istream& aStream);
istream& readFile(istream& aStream) {return readToDelimiter(aStream, '\0');}
istream& readLine(istream& aStream) {return readToDelimiter(aStream, '\n');}
istream& appendToDelimiter(istream&
istream& appendAToken(istream& aStream);
istream& appendFile(istream& aStream) {return appendToDelimiter(aStream,
istream& appendLine(istream& aStream) {return appendToDelimiter(aStream,
ADPString& append(const char* cs, int num = -1);
ADPString& append(char aChar, int num = -1);
ADPString& append(const ADPString& aStr, int num = -1);
ADPString& append(long x);
ADPString& append(unsigned long x);
ADPString& append(float x);
ADPString& append(double x);
int collate(const char* cs) const;
int collate(const ADPString& cs) const {return collate(cs.c_str());}
int capacity() const {return _allocatedSize;}
int capacity(int aSize);
// Include the end points
ADPString subString(int begin_index, int end_index=-1) const;
// Match as in a file match wild card
int fnmatch(const char* s) const;
int fnmatch(const ADPString& s) const;
static int fnmatch(const char* str, const char* wild, int case_senstive);
static int fnmatch(const ADPString& str, const char* wild, int case_senstive);
static int fnmatch(const char* str, const ADPString& wild, int case_senstive);
static int fnmatch(const ADPString& str, const ADPString& wild, int case_senstive);
static int fnmatch_no_periods_at_end(
protected:
void setString(const ADPString& aString);
void setString(const char* aString, int theLength);
void setString(char aChar, int theLength);
void setString(const char* aString);
int strContainsPtr(const char* aStr);
int _length;
int _allocatedSize;
int _caseSensitive;
char* _data;
static int _extra;
static int _cleanup;
#ifdef TestADPString
public:
static int test();
#endif
};
inline istream& operator>>(istream& strm, ADPString& s) {return s.readAToken(strm);}
inline ostream& operator<<(ostream& strm, const ADPString& s) {return strm << s.c_str();}
inline ADPString& operator<<(ADPString& s, const ADPString& x) {return s.append(x);}
inline ADPString& operator<<(ADPString& s, const char* x) {return s.append(x);}
inline ADPString& operator<<(ADPString& s, char x) {return s.append(x);}
inline ADPString& operator<<(ADPString& s, const std::string x) {return s.append(x.c_str());}
inline ADPString& operator<<(ADPString& s, short x) {return s.append((long) x);}
inline ADPString& operator<<(ADPString& s, int x) {return s.append((long) x);}
inline ADPString& operator<<(ADPString& s, long x) {return s.append(x);}
inline ADPString& operator<<(ADPString& s, unsigned short x) {return s.append((unsigned long) x);}
inline ADPString& operator<<(ADPString& s, unsigned int x) {return s.append((unsigned long) x);}
inline ADPString& operator<<(ADPString& s, unsigned long x) {return s.append(x);}
inline ADPString& operator<<(ADPString& s, float x) {return s.append(x);}
inline ADPString& operator<<(ADPString& s, double x) {return s.append(x);}
#endif
++++++++++++++++++++++++++
//************************
//** **
//** Copyright 1996-2002 by Andrew D. Pitonyak **
//** **
//** This software has been protected by the standard Copyleft GPL **
//** **
//** This program is free software; you can redistribute it and/or **
//** modify it under the terms of the GNU General Public License **
//** as published by the Free Software Foundation; either version 2 **
//** of the License, or (at your option) any later version. **
//** **
//** This program is distributed in the hope that it will be useful, **
//** but WITHOUT ANY WARRANTY; without even the implied warranty of **
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
//** GNU General Public License for more details. **
//** **
//** You should have received a copy of the GNU General Public License **
//** along with this program; if not, write to the Free Software **
//** Foundation, Inc., 59 Temple Place - **
//** Suite 330, Boston, MA 02111-1307, USA. **
//** **
//** Andrew D. Pitonyak **
//** 4446 Mobile Drive #105 **
//** Columbus, OH 43220 **
//** code@pitonyak.org **
//** **
//************************
//** **
//** This contains a simple string class. It is kind of wasteful given **
//** that a few extra pieces such as length is stored for each and every **
//** string and given that each string stores the case sensitivity **
//** **
//** This is meant for simple things. I did not use the built in string **
//** types because then the code would be compiler dependent. I hate that**
//** **
//** April 28, 1998 **
//** Added "append" versions of I/O functions and changed the read **
//** functions to clear the string first. Also changed unsigned long **
//** variables to use unsigned int. **
//** **
//** May 8, 1998 **
//** Added the shiftDown() function **
//** **
//** March 10, 2002 **
//** The code would not even compile. There were many errors. **
//** I have no idea what I did or when, but this is clearly a **
//** modified copy of the original. I probably added functions **
//** also present in RogueWave. **
//** **
//** I changed all unsigned ints to just int. **
//** **
//** April 2, 2002 **
//** Added new methods like fnMatch(), startsWith(), endsWith() **
//** countChar(). Added streaming operators and append() to more **
//** easily add more types into a string. Added limited support **
//** to create an ADPString from an std::string **
//** Added imporved testing code and fixed a few bugs dealing with **
//** repeated characters. **
//** **
//************************
#include "adpstrng.hpp"
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
int ADPString::_extra = 20;
int ADPString::_cleanup = 100;
//************************
//** **
//** Input : const ADPString& : Set to this string, **
//** int : 0 means case insensitive **
//** int : number of chars to include. <1 means all **
//** **
//** Output: None **
//** **
//** Notes : Constructor **
//** **
//************************
ADPString::ADPString(const
_length(0), _allocatedSize(0), _caseSensitive(isCase), _data(0)
{
setString(aString);
if ( num > 0 && num < length() )
resize(num);
}
//************************
//** **
//** Input : const std::string& : Set to this string, **
//** int : 0 means case insensitive **
//** int : number of chars to include. <1 means all **
//** **
//** Output: None **
//** **
//** Notes : Constructor **
//** **
//************************
ADPString::ADPString(const
_length(0), _allocatedSize(0), _caseSensitive(isCase), _data(0)
{
setString(aString.c_str())
if ( num > 0 && num < length() )
resize(num);
}
//************************
//** **
//** Input : const ADPString& : Set to this string, **
//** int : 0 means case insensitive **
//** int : number of chars to include. <1 means all **
//** **
//** Output: None **
//** **
//** Notes : Constructor **
//** **
//************************
ADPString::ADPString(const
_length(0), _allocatedSize(0), _caseSensitive(isCase), _data(0)
{
setString(aString);
if ( num > 0 && num < length() )
resize(num);
}
//************************
//** **
//** Input : const ADPString& : Set to this string, **
//** int : 0 means case insensitive **
//** int : number of chars to include. <1 means all **
//** **
//** Output: None **
//** **
//** Notes : Constructor **
//** **
//************************
ADPString::ADPString(char aChar, int isCase, int num) :
_length(0), _allocatedSize(0), _caseSensitive(isCase), _data(0)
{
setString(aChar, num);
if ( num > 0 && num < length() )
resize(num);
}
//************************
//** **
//** Input : None **
//** **
//** Output: None **
//** **
//** Notes : Destructor **
//** **
//************************
ADPString::~ADPString()
{
delete[] _data;
_length = 0;
_allocatedSize = 0;
}
//************************
//** **
//** Input : const char* : Set to this string, non-null if len > 0 **
//** int : Length of the string, assumed correct **
//** **
//** Output: None **
//** **
//** Notes : Copies the specified string to this string. **
//** The _data is never ever left as null **
//** **
//************************
void ADPString::setString(const
{
if (capacity() <= theLength || theLength + _cleanup + 1 < capacity())
{
//
// Either, there is not enough space, or there is too much space
//
grow(theLength + 1 + _extra, 0);
}
//
// Told grow not to copy the string, so the _length is 0 and (*data == 0)
//
if (theLength != 0)
{
strcpy(_data, aString);
}
_length = theLength;
if (_data != 0)
{
_data[_length] = 0;
}
}
//************************
//** **
//** Input : char : Set to this character **
//** int : Length of the string when done **
//** **
//** Output: None **
//** **
//** Notes : **
//** **
//************************
void ADPString::setString(char aChar, int theLength)
{
resize(0);
append(aChar, theLength);
}
//************************
//** **
//** Input : const char* : Set to this string, null is OK **
//** **
//** Output: None **
//** **
//** Notes : Copies the specified string to this string. **
//** The _data is never ever left as null **
//** **
//************************
void ADPString::setString(const
{
setString(charPtr, charPtr ? strlen(charPtr) : 0);
}
//************************
//** **
//** Input : const ADPString& : Set to this string, **
//** **
//** Output: None **
//** **
//** Notes : Copies the specified string to this string. **
//** The _data is never ever left as null **
//** **
//************************
void ADPString::setString(const
{
setString(aString.c_str(),
}
//************************
//** **
//** Input : const ADPString& : String to assign **
//** **
//** Output: const ADPString& : reference to this **
//** **
//** Notes : Assignment operator **
//** **
//************************
const ADPString& ADPString::operator=(const
{
if (this != &aString)
setString(aString);
return *this;
}
//************************
//** **
//** Input : const char* : String to assign **
//** **
//** Output: const char* : Pointer to the data **
//** **
//** Notes : Assignment operator **
//** **
//************************
const char* ADPString::operator=(const
{
if (aString == 0) {
setString(aString, 0);
} else if (!strContainsPtr(aString))
//
// There is no overlap
//
setString(aString, strlen(aString));
} else {
//
// There is overlap darn it so be safe and who cares
// about efficiency. If you do a lot of this, then make
// it more efficient. I am assuming that this is infrequent
// enough that I opted to take the quick way out.
//
ADPString(aString);
setString(aString);
}
return c_str();
}
//************************
//** **
//** Input : character which is assigned to the string **
//** **
//** Output: the character which was assigned **
//** **
//** Notes : Assignment operator **
//** **
//************************
char ADPString::operator=(char c)
{
truncate(0);
operator+=(c);
return c;
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if true, zero if false **
//** **
//************************
int ADPString::operator==(cons
{
return cmp(aString) == 0;
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if true, zero if false **
//** **
//************************
int ADPString::operator!=(cons
{
return cmp(aString) != 0;
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if true, zero if false **
//** **
//************************
int ADPString::operator< (const ADPString& aString) const
{
return cmp(aString) < 0;
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if true, zero if false **
//** **
//************************
int ADPString::operator> (const ADPString& aString) const
{
return cmp(aString) > 0;
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if true, zero if false **
//** **
//************************
int ADPString::operator<=(cons
{
return cmp(aString) <= 0;
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if true, zero if false **
//** **
//************************
int ADPString::operator>=(cons
{
return cmp(aString) >= 0;
}
//************************
//** **
//** Input : char : Object against which to compare **
//** **
//** Output: int : Number of times this character is in the string **
//** **
//************************
int ADPString::countChar(char c) const
{
int cnt = 0;
if (length() > 0)
{
for (const char* cursor = _data; *cursor != 0; ++cursor)
{
if (*cursor == c)
++cnt;
}
}
return cnt;
}
//************************
//** **
//** Input : const char* : Object against which to compare **
//** **
//** Output: int : non-zero if this ends with str, zero otherwise **
//** **
//************************
int ADPString::endsWith(const char* str) const
{
int n = (str != 0) ? strlen(str) : 0;
if (n == 0)
return 1;
if (n > length())
return 0;
return strncmp(_data + (length() - n), str, n) == 0;
}
//************************
//** **
//** Input : char : Object against which to compare **
//** **
//** Output: int : non-zero if this ends with c, zero otherwise **
//** **
//************************
int ADPString::endsWith(char c) const
{
return (_length > 0) && (_data[_length-1] == c);
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if this ends with str, zero otherwise **
//** **
//************************
int ADPString::endsWith(const ADPString& str) const
{
if (str.length() > length())
return 0;
return strncmp(_data + (length() - str.length()), str.c_str(), str.length()) == 0;
}
//************************
//** **
//** Input : const char* : Object against which to compare **
//** **
//** Output: int : non-zero if this starts with str, zero otherwise **
//** **
//************************
int ADPString::startsWith(cons
{
int n = (str != 0) ? strlen(str) : 0;
if (n == 0)
return 1;
if (n > length())
return 0;
return strncmp(_data, str, n) == 0;
}
//************************
//** **
//** Input : char : Object against which to compare **
//** **
//** Output: int : non-zero if this starts with str, zero otherwise **
//** **
//************************
int ADPString::startsWith(char
{
return (_length > 0) && (*_data == c);
}
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : non-zero if this starts with str, zero otherwise **
//** **
//************************
int ADPString::startsWith(cons
{
if (str.length() > length())
return 0;
return strncmp(_data, str.c_str(), str.length()) == 0;
}
#if defined( _ADP_UNIX_ )
// Did you know that strcasecmp is completely
// bad bad bad under cygwin?
// I did!
int adp_stricmp(const char* c1, const char* c2)
{
int rc = 0;
if (c1 && c2)
{
//
// There are no NULL pointers, not that there should ever be...
//
while (!rc)
{
rc = toupper(*c1) - toupper(*c2);
if (*c1 == 0)
{
return rc;
}
++c1;
++c2;
}
}
else
{
//
// There is at least one NULL
//
if (c1)
rc = 1;
else if (c2)
rc = -1;
}
return rc;
}
#endif
//************************
//** **
//** Input : const ADPString& : Object against which to compare **
//** **
//** Output: int : Negative if this is less than aString **
//** zero if the strings are equal **
//** Posative if this is greater than aString **
//** **
//** Notes : Not case sensitive takes precidence **
//** **
//************************
int ADPString::cmp(const ADPString& aString) const
{
int rc = 0;
const char* c1 = c_str();
const char* c2 = aString.c_str();
if (c1 && c2) {
//
// There are no NULL pointers, not that there should ever be...
//
if (!caseSensitive() || !aString.caseSensitive()) {
#if defined( _ADP_UNIX_ )
rc = adp_stricmp(c1, c2);
#else
rc = stricmp(c1, c2);
#endif
} else {
rc = strcmp(c1, c2);
}
} else {
//
// There is at least one NULL
//
if (c1)
rc = 1;
else if (c2)
rc = -1;
// else
// rc = 0;
}
return rc;
}
//************************
//** **
//** Input : const char* : Object against which to compare **
//** **
//** Output: int : non-zero if true, zero if false **
//** **
//** Notes : Compare to a const char* **
//** **
//************************
int ADPString::cmp(const char* aString) const
{
int rc = 0;
if (c_str() && aString)
{
//
// There are no NULL pointers, not that there should ever be...
//
if (caseSensitive())
{
rc = strcmp(c_str(), aString);
}
else
{
#if defined( _ADP_UNIX_ )
rc = adp_stricmp(c_str(), aString);
#else
rc = stricmp(c_str(), aString);
#endif
}
}
else
{
//
// There is at least one NULL
//
if (c_str())
rc = 1;
else if (aString)
rc = -1;
// else
// rc = 0;
}
return rc;
}
int ADPString::collate(const char* cs) const
{
return cs ? strcoll(c_str(), cs) : strcoll(c_str(), "");
}
//************************
//** **
//** Input : const char* : Object against which to compare **
//** **
//** Output: int : non-zero the pointer intersects the allocated area **
//** **
//** Notes : **
//** **
//************************
int ADPString::strContainsPtr(
{
return _data <= aStr && aStr <= _data + capacity();
}
//************************
//** **
//** Input : x - number to append to this string **
//** **
//** Output: reference to self **
//** **
//** Notes : **
//** **
//************************
ADPString& ADPString::append(long x)
{
char buf[100];
sprintf(buf, "%ld", x);
operator+=(buf);
return *this;
}
//************************
//** **
//** Input : x - number to append to this string **
//** **
//** Output: reference to self **
//** **
//** Notes : **
//** **
//************************
ADPString& ADPString::append(unsigned
{
char buf[100];
sprintf(buf, "%lu", x);
operator+=(buf);
return *this;
}
//************************
//** **
//** Input : x - number to append to this string **
//** **
//** Output: reference to self **
//** **
//** Notes : **
//** **
//************************
ADPString& ADPString::append(float x)
{
char buf[100];
sprintf(buf, "%f", x);
operator+=(buf);
return *this;
}
//************************
//** **
//** Input : x - number to append to this string **
//** **
//** Output: reference to self **
//** **
//** Notes : **
//** **
//************************
ADPString& ADPString::append(double x)
{
char buf[100];
sprintf(buf, "%f", x);
operator+=(buf);
return *this;
}
//************************
//** **
//** Input : const char* : String to append to the end **
//** int : Number of times to append it **
//** **
//** Output: reference to self **
//** **
//** Notes : **
//** **
//************************
ADPString& ADPString::append(const char* cs, int num)
{
if (cs)
{
if (num < 1)
num = 1;
if (strContainsPtr(cs))
{
ADPString aStr(cs);
append(aStr, num);
}
else
{
int str_len = strlen(cs);
int newSize = length() + _extra + 1 + str_len * num;
grow(newSize, 1);
for (int i=0; i<num; ++i)
strcat(_data, cs);
_length += str_len * num;
}
}
return *this;
}
//************************
//** **
//** Input : char : Character to append to the end **
//** int : Number of times to append it **
//** **
//** Output: reference to self **
//** **
//** Notes : **
//** **
//************************
ADPString& ADPString::append(char aChar, int num)
{
if (num < 0)
num = 1;
if (capacity() <= num + length() + 1 || num + _cleanup + 1 < capacity())
{
//
// Either, there is not enough space, or there is too much space
//
grow(capacity() <= num + length() + 1 + _extra, 1);
}
for (int i=0; i<num; ++i)
_data[_length++] = aChar;
_data[_length] = 0;
return *this;
}
//************************
//** **
//** Input : const ADPString& : String to append to the end **
//** int : Number of times to append it **
//** **
//** Output: reference to self **
//** **
//** Notes : **
//** **
//************************
ADPString& ADPString::append(const ADPString& aStr, int num)
{
return append(aStr.c_str(), num);
}
//************************
//** **
//** Input : const std::string& : Object to add at the end **
//** **
//** Output: None **
//** **
//** Notes : Add a string to the end of this one **
//** **
//************************
void ADPString::operator+=(cons
{
return operator+=(aString.c_str()
}
//************************
//** **
//** Input : const ADPString& : Object to add at the end **
//** **
//** Output: None **
//** **
//** Notes : Add a string to the end of this one **
//** **
//************************
void ADPString::operator+=(cons
{
if (aString.length() > 0) {
if (capacity() <= length() + aString.length())
grow(length() + aString.length() + 1 + _extra, 1);
//
// So why did I not use strcat? Because the strings may be the same.
//
if (this != &aString) {
strcat(_data, aString.c_str());
_length += aString.length();
} else {
int finalLength = length() + aString.length();
for (int i=length(); i < finalLength; ++i)
_data[i] = aString._data[i-length()];
_length += aString.length();
_data[length()] = 0;
}
}
doCleanup();
}
//************************
//** **
//** Input : const char* : Object to add at the end **
//** **
//** Output: None **
//** **
//** Notes : Add a string to the end of this one **
//** **
//************************
void ADPString::operator+=(cons
{
int theLen = aString ? strlen(aString) : 0;
if (theLen > 0) {
if (strContainsPtr(aString)) {
//
// There is overlap in the range so the copy string
// is contained in the target.
//
_allocatedSize = length() + theLen + 1 + _extra;
char* temp = new char[_allocatedSize];
if (_data)
strcpy(temp, _data);
else
*temp = 0;
strcat(temp, aString);
delete[] _data;
_data = temp;
} else {
//
// There is no overlap so allocate extra space if it is needed
// The ranges are completely separate strings.
//
if (capacity() <= length() + theLen)
grow(length() + theLen + 1 + _extra, 1);
strcat(_data, aString);
}
_length += theLen;
}
doCleanup();
}
//************************
//** **
//** Input : char : Object to add at the end **
//** **
//** Output: None **
//** **
//** Notes : Add a string to the end of this one **
//** **
//************************
void ADPString::operator+=(char
{
char temp[2];
temp[0] = aChar;
temp[1] = 0;
operator+=(temp);
}
//************************
//** **
//** Input : int : Offset into the array **
//** **
//** Output: Character at the entered offset **
//** **
//** Notes : bounds checking is done. A zero is returned if out of bounds**
//** **
//************************
char ADPString::operator[](int pos) const
{
if (pos <= length())
return _data[pos];
else
return 0;
}
//************************
//** **
//** Input : int : Offset into the array **
//** **
//** Output: Character at the entered offset **
//** **
//** Notes : bounds checking is done. A zero is returned if out of bounds**
//** **
//************************
char& ADPString::operator[](int pos)
{
static char* badBoy = "";
char* trickeyBadBad = (char *) badBoy;
if (pos <= length())
return _data[pos];
else
return trickeyBadBad[0];
}
//************************
//** **
//** Input : int : offset **
//** **
//** Output: None **
//** **
//** Notes : The offset will be the new length **
//** **
//************************
void ADPString::truncate(int pos)
{
if (pos < _length) {
_length = pos;
_data[pos] = 0;
}
doCleanup();
}
//************************
//** **
//** Input : int : offset **
//** **
//** Output: None **
//** **
//** Notes : This will remove stuff from the front of a string **
//** The character at pos is moved to 0 **
//** **
//************************
void ADPString::shiftDown(int pos)
{
assert(_data != 0);
if (pos >= length()) {
_length = 0;
_data[0] = 0;
} else if (pos > 0) {
for (int i=pos; i <= length(); ++i)
_data[i-pos] = _data[i];
_length -= pos;
}
doCleanup();
}
//************************
//** **
//** Input : character to find **
//** **
//** Output: Index of the first occurence, or -1 if not found **
//** **
//** Notes : **
//** **
//************************
int ADPString::findFirst(int c) const
{
int i = 0;
while (i < length() && _data[i] != c)
++i;
return i < length() && _data[i] == c ? i : -1;
}
//************************
//** **
//** Input : character to find **
//** **
//** Output: Index of the last occurence, or -1 if not found **
//** **
//** Notes : **
//** **
//************************
int ADPString::findLast(int c) const
{
int i = length() - 1;
while (i >= 0 && _data[i] != c)
--i;
return i >= 0 && _data[i] == c ? i : -1;
}
//************************
//** **
//** Input : None **
//** **
//** Output: None **
//** **
//** Notes : Remove extra spaces from the end of the string **
//** **
//************************
void ADPString::trimEnd()
{
while (_length > 0 && isspace(_data[_length-1]))
_data[--_length] = 0;
truncate(_length);
}
//************************
//** **
//** Input : None **
//** **
//** Output: None **
//** **
//** Notes : Remove extra spaces from the front of the string **
//** **
//************************
void ADPString::trimFront()
{
int pos = 0;
while (pos < _length && isspace(_data[pos]))
++pos;
shiftDown(pos);
}
//************************
//** **
//** Input : None **
//** **
//** Output: None **
//** **
//** Notes : Remove extra spaces from the ends of the string **
//** **
//************************
void ADPString::doCleanup()
{
if (capacity() - length() > cleanup())
grow(length() + extra() + 1, 1);
}
//************************
//** **
//** Input : pos : Hint about how much allocated space should there be. **
//** **
//** Output: None **
//** **
//** Notes : Never destroys part of the string. **
//** **
//************************
int ADPString::capacity(int pos)
{
if (pos > length())
grow(pos, 1);
return capacity();
}
//************************
//** **
//** Input : pos : How much allocated space should there be. **
//** copyString : 1 if the existing string should be preserved **
//** **
//** Output: None **
//** **
//** Notes : Make certain that the only (pos) space is allocated **
//** **
//************************
void ADPString::grow(int pos, int copyString)
{
if (pos == 0)
{
delete[] _data;
_data = 0;
_allocatedSize = pos;
_length = 0;
}
else
{
//
// If it needs to be smaller, then simply throw away part
// of the string. Note that _data can not be NULL if
// _allocatedSize => pos
//
if (capacity() >= pos)
{
_data[pos-1] = 0;
if (_length > pos)
_length = pos;
}
_allocatedSize = pos;
char *temp = new char[_allocatedSize];
*temp = 0;
if (_data)
{
if (copyString)
strcpy(temp, _data);
else
_length = 0;
delete[] _data;
}
_data = temp;
}
}
//************************
//** **
//** Input : aChar : a character **
//** **
//** Output: None. **
//** **
//** Notes : Force the last character to be aChar **
//** **
//************************
void ADPString::forceLastChar(c
{
if (!lastCharIs(aChar))
operator+=(aChar);
}
//************************
//** **
//** Input : None **
//** **
//** Output: None **
//** **
//** Notes : Convert the string to upper case **
//** **
//************************
void ADPString::toUpper()
{
for (int i = 0; i < length(); ++i)
if (islower(_data[i]))
_data[i] = toupper(_data[i]);
}
//************************
//** **
//** Input : None **
//** **
//** Output: None **
//** **
//** Notes : Convert string to lower case **
//** **
//************************
void ADPString::toLower()
{
for (int i = 0; i < length(); ++i)
if (isupper(_data[i]))
_data[i] = tolower(_data[i]);
}
//************************
//** **
//** Input : istream& - stream from which to read **
//** char - delimiter (read to this character **
//** **
//** Output: istream& - **
//** **
//** Notes : Read the stream into the string until the delimiter is found**
//** **
//************************
istream& ADPString::readToDelimiter
{
truncate(0);
return appendToDelimiter(aStream,
}
//************************
//** **
//** Input : istream& - stream from which to read **
//** char - delimiter (read to this character **
//** **
//** Output: istream& - **
//** **
//** Notes : Read the stream into the string until the delimiter is found**
//** **
//************************
istream& ADPString::appendToDelimit
{
int done = 0;
int extraAmt = (extra() > 100) ? extra() : 150;
//
// Make certain that there is enough space for more characters
//
if (_data == 0 || capacity() < _length + 10)
grow(_allocatedSize + extraAmt, 1);
while (done == 0 && aStream.good()) {
aStream.get(_data+length()
_length += strlen(_data+length());
if (aStream.good()) {
if (aStream.peek() == aDelimiter) {
//
// Throw away the delimiter
//
char temp;
aStream.get(temp);
done = 1;
} else {
//
// No errors so I must need more space.
//
grow(capacity() + extraAmt, 1);
}
}
}
return aStream;
}
//************************
//** **
//** Input : istream& - read from the stream **
//** **
//** Output: istream& **
//** **
//** Notes : skip initial white space, then read until white space is **
//** found again. **
//** **
//************************
istream& ADPString::readAToken(istr
{
truncate(0);
return appendAToken(aStream);
}
//************************
//** **
//** Input : istream& - read from the stream **
//** **
//** Output: istream& **
//** **
//** Notes : skip initial white space, then read until white space is **
//** found again. **
//** **
//************************
istream& ADPString::appendAToken(is
{
int done = 0;
int extraAmt = (extra() > 100) ? extra() : 150;
if (_data == 0 || capacity() < _length + 10)
grow(_allocatedSize + extraAmt, 1);
char temp = 0;
//
// Remove white space
//
while (aStream.good() && isspace(aStream.peek()))
aStream.get(temp);
while (done == 0 && aStream.good()) {
aStream.get(temp);
if (!isspace(temp)) {
_data[_length++] = temp;
if (length() == capacity() - 1) {
_data[_length] = 0;
grow(capacity() + extraAmt, 1);
}
} else {
done = 1;
}
}
_data[_length] = 0;
return aStream;
}
//************************
//** **
//** Input : begin_index - first character to include. < 0 means 0 **
//** end_index - last charcter to include. < 0 means to end **
//** **
//** Output: The substring including the end points **
//** **
//** Notes : **
//** **
//************************
ADPString ADPString::subString(int begin_index, int end_index) const
{
ADPString rc;
if (length() <= 0 || length() <= begin_index)
return rc;
if (end_index < 0 || length() <= end_index)
end_index = length() - 1;
if (begin_index < 0)
begin_index = 0;
rc = c_str();
rc.truncate(end_index + 1);
rc.shiftDown(begin_index);
return rc;
}
//************************
//** **
//** Input : s - wild card matching file name. **
//** **
//** Output: non-zero on a match, 0 otherwise **
//** **
//** Notes : A trailing '.' matches the end of the string as well **
//** **
//************************
int ADPString::fnmatch(const char* s) const
{
return fnmatch(*this, ADPString(s), caseSensitive());
}
//************************
//** **
//** Input : str - file name to match to the wild card **
//** wild - wild card to use to match the file name **
//** **
//** Output: non-zero on a match, 0 otherwise **
//** **
//** Notes : See notes on the version that takes two const ADPStrings& **
//** **
//************************
int ADPString::fnmatch(const char* str, const char* wild, int case_senstive)
{
return fnmatch(ADPString(str), ADPString(wild), case_senstive);
}
//************************
//** **
//** Input : str - file name to match to the wild card **
//** wild - wild card to use to match the file name **
//** **
//** Output: non-zero on a match, 0 otherwise **
//** **
//** Notes : See notes on the version that takes two const ADPStrings& **
//** **
//************************
int ADPString::fnmatch(const ADPString& str, const char* wild, int case_senstive)
{
return fnmatch(str, ADPString(wild), case_senstive);
}
//************************
//** **
//** Input : str - file name to match to the wild card **
//** wild - wild card to use to match the file name **
//** **
//** Output: non-zero on a match, 0 otherwise **
//** **
//** Notes : See notes on the version that takes two const ADPStrings& **
//** **
//************************
int ADPString::fnmatch(const char* str, const ADPString& wild, int case_senstive)
{
return fnmatch(ADPString(str), wild, case_senstive);
}
//************************
//** **
//** Input : str - file name to match to the wild card **
//** wild - wild card to use to match the file name **
//** **
//** Output: non-zero on a match, 0 otherwise **
//** **
//** Notes : **
//** An effort was made to follow current convention of "*.*" matching **
//** everything and "*." matching names with no period. This is what **
//** fnmatch() does before calling fnmatch_no_periods_at_end(
//** **
//************************
int ADPString::fnmatch(const ADPString& str, const ADPString& wild, int case_sensitive)
{
// There is no period in the file name so
// lets see if we have either a wild card
// ending with a period (in which case the period is removed)
// or ending with a ".*" in which case that is removed instead.
if (str.countChar('.') == 0)
{
int period_count = wild.countChar('.');
if (period_count == 0)
return fnmatch_no_periods_at_end(
if (period_count > 1)
return 0;
ADPString temp_wild(wild);
while (temp_wild.endsWith('*'))
temp_wild.truncate(wild.le
if (temp_wild.endsWith('.'))
temp_wild.truncate(wild.le
return fnmatch_no_periods_at_end(
}
return fnmatch_no_periods_at_end(
}
int ADPString::fnmatch_no_peri
{
if (str == 0)
str = "";
if (wild == 0)
wild = "";
if (*str == 0)
{
return (*wild == 0) || (*wild == '*' && wild[1] == 0) ? 1 : 0;
}
while (*str != 0 && *wild != 0)
{
if (*str == *wild || *wild == '?' || (case_sensitive != 0 && toupper(*str) == toupper(*wild)))
{
++str;
++wild;
}
else if (*wild == '*')
{
while (*wild == '*')
++wild;
if (*wild == 0)
return 1;
// wild card match
// try a non-greedy match first because it is
// easier to write.
// First check a zero length match!
while (*str != 0)
{
if (fnmatch_no_periods_at_end
return 1;
else
++str;
}
return 0;
}
else
{
return 0;
}
}
// Ignore any trailing wild cards
while (*wild == '*')
++wild;
// See if have ended for both or if
// the string has ended and the wild card contains a trailing '.'
// This is not absolutely correct but
if (*str == *wild)
return 1;
return 0;
}
//************************
//** **
//** Input : s - directory wild card matching. **
//** **
//** Output: non-zero on a match, 0 otherwise **
//** **
//** Notes : A trailing '.' matches the end of the string as well **
//** **
//************************
int ADPString::fnmatch(const ADPString& s) const
{
return fnmatch(*this, s, caseSensitive());
}
#ifdef TestADPString
#include <iostream.h>
//************************
//** **
//** Input : None **
//** **
//** Output: 1 if passes, 0 otherwise **
//** **
//** Notes : This is perhaps not as complete as it could be **
//** **
//************************
int ADPString::test()
{
int passed = 1;
const char* alphaLower = "abcdefghijklmnopqrstuvwxy
const char* alphaUpper = "ABCDEFGHIJKLMNOPQRSTUVWXY
ADPString s1;
ADPString s2(s1);
ADPString s3(alphaLower);
ADPString s4(alphaUpper);
ADPString s5(s3);
if (s1.length() != 0 || s2.length() != 0 || s3.length() != (int)strlen(alphaLower) || s3.length() != s4.length() || s3.length() != s5.length()) {
passed = 0;
cout << endl << "Failed the length checks" << endl;
}
if (passed) {
passed = s1 == s2 && s3 == s4 && s3 == s3 && s1 < s3 && s2 <= s4 && s3 <= s4 && s3 >= s4 && !(s3 < s4) && !(s3 > s4) && s5 == s3;
if (!passed)
cout << endl << "Failed comparisons (1)" << endl;
s3.caseSensitive(1);
s4.caseSensitive(1);
passed = passed && s3 != s4;
if (!passed)
cout << endl << "Failed comparisons (2)" << endl;
passed = passed && s3 == s3;
if (!passed)
cout << endl << "Failed comparisons (3)" << endl;
passed = passed && s3 > s4;
if (!passed)
cout << endl << "Failed comparisons (4)" << endl;
passed = passed && s3 >= s4;
if (!passed)
cout << endl << "Failed comparisons (5)" << endl;
passed = passed && !(s3 < s4);
if (!passed)
cout << endl << "Failed comparisons (6)" << endl;
passed = passed && !(s3 <= s4);
if (!passed)
cout << endl << "Failed comparisons (7)" << endl;
s3.caseSensitive(0);
s4.caseSensitive(0);
if (!passed)
cout << endl << "Failed comparisons (8)" << endl;
}
if (passed){
s3 += s1;
s3 += "";
s3 += alphaLower;
s5 += s5;
passed = s5 == s3;
if (!passed)
cout << endl << "Failed additions(1)" << endl;
passed = passed && s3.length() == s5.length();
if (!passed)
cout << endl << "Failed additions(2)" << endl;
passed = passed && s3.length() == 2*(int)strlen(alphaLower);
if (!passed)
cout << endl << "Failed additions(3)" << endl;
}
if (passed) {
s3 = " ";
s4 = s3;
s4 += s3; // 2 spaces
s4 += s4; // 4 spaces
s3 += s4; // 5 spaces
s3 += "123456";
s3 += s4;
s5 = " 123456 ";
s1 = s4;
s1.trimEnd();
passed = passed && s1.length() == 0;
s1 = s4;
s1.trimFront();
passed = passed && s1.length() == 0;
s1 = s3;
s2 = s3;
s4 = s3;
s1.trimEnd();
s2.trimFront();
s4.trimAll();
passed = passed && s3 == s5 && s3.length() == 15 && s4.length() == 6 && s1.length() == 11 && s2.length() == 10;
if (!passed)
cout << endl << "Failed trim" << endl;
}
if (passed)
{
ADPString cn1('a', 0, -1);
ADPString c0('a', 0, 0);
ADPString c1('a', 0, 1);
ADPString c2('a', 0, 2);
ADPString c5('a', 0, 5);
ADPString tst;
if (c0 != tst)
{
passed = 0;
cout << "Char constructor failure with c0 = \"" << c0 << "\" rather than \"" << tst << "\"" << endl;
}
tst = "a";
if (cn1 != c1 || tst != c1)
{
passed = 0;
cout << "Char constructor failure with cn1 = \"" << cn1 << "\" rather than \"" << tst << "\"" << endl;
}
tst += tst;
if (c2 != tst)
{
passed = 0;
cout << "Char constructor failure with c2 = \"" << c2 << "\" rather than \"" << tst << "\"" << endl;
}
tst += tst;
tst += 'a';
if (c5 != tst)
{
passed = 0;
cout << "Char constructor failure with c5 = \"" << c5 << "\" rather than \"" << tst << "\"" << endl;
}
if (passed == 0)
{
cout << endl << "Failed constructing strings from characters" << endl;
cout << "cn1 = \"" << cn1 << "\"" << endl;
cout << "c0 = \"" << c0 << "\"" << endl;
cout << "c1 = \"" << c1 << "\"" << endl;
cout << "c2 = \"" << c2 << "\"" << endl;
cout << "c5 = \"" << c5 << "\"" << endl;
}
}
if (passed)
{
s1 = alphaLower;
s2 = s1;
if (!s1.startsWith(s2) || !s1.startsWith(alphaLower)
{
passed = 0;
cout << "Initial starts with test failed" << endl;
}
if (!s1.startsWith("") || !s1.startsWith("a") || !s1.startsWith("abc"))
{
passed = 0;
cout << "Secondary starts with test failed" << endl;
}
if (!s1.endsWith(s2) || !s1.endsWith(alphaLower) || !s1.endsWith('z'))
{
passed = 0;
cout << "Initial ends with test failed" << endl;
}
if (!s1.endsWith("") || !s1.endsWith("z") || !s1.endsWith("xyz"))
{
passed = 0;
cout << "Secondary ends with test failed" << endl;
}
}
if (passed)
{
s1 = "";
s2 = "";
s1.append('a', 0);
if (s1 != s2)
{
cout << "(0) Appending single chars, I have \"" << s1 << "\" rather than \"" << s2 << "\"" << endl;
passed = 0;
}
s1 = "";
s2 = "a";
s1.append('a', -1);
if (s1 != s2)
{
cout << "(1) Appending single chars, I have \"" << s1 << "\" rather than \"" << s2 << "\"" << endl;
passed = 0;
}
s2 += s2;
s1.append('a', 1);
if (s1 != s2)
{
cout << "(2) Appending single chars, I have \"" << s1 << "\" rather than \"" << s2 << "\"" << endl;
passed = 0;
}
s1 = "";
s2 = "aa";
s1.append('a', 2);
if (s1 != s2)
{
cout << "(3) Appending single chars, I have \"" << s1 << "\" rather than \"" << s2 << "\"" << endl;
passed = 0;
}
s2 = "aaaa";
s1.append('a', 2);
if (s1 != s2)
{
cout << "(4) Appending single chars, I have \"" << s1 << "\" rather than \"" << s2 << "\"" << endl;
passed = 0;
}
if (!passed)
cout << "Failed appending single characters" << endl;
}
if (passed)
{
s1 = "";
s2 = "";
s1.append(s1, 0);
if (s1 != s2)
{
cout << " (0) I expected that \"" << s1 << "\" == \"" << s2 << "\"" << endl;
passed = 0;
}
s1 = "";
s1.append(s1, -1);
if (s1 != s2)
{
cout << " (1) I expected that \"" << s1 << "\" == \"" << s2 << "\"" << endl;
passed = 0;
}
s1 = "";
s1.append(s1, 4);
if (s1 != s2)
{
cout << " (2) I expected that \"" << s1 << "\" == \"" << s2 << "\"" << endl;
passed = 0;
}
s2 = "a";
s1.append(s2, 1);
if (s1 != s2)
{
cout << " (3) I expected that \"" << s1 << "\" == \"" << s2 << "\"" << endl;
passed = 0;
}
s2 = "aaa";
s1.append(s1, 2);
if (s1 != s2)
{
cout << " (4) I expected that \"" << s1 << "\" == \"" << s2 << "\"" << endl;
passed = 0;
}
s1 = "aaa";
s2 = "aaaaaaaaaaaa";
s1.append(s1, 3);
if (s1 != s2)
{
cout << " (5) I expected that \"" << s1 << "\" == \"" << s2 << "\"" << endl;
passed = 0;
}
s2.append(s1.c_str() + (s2.length() - 2), 3);
s1.append(s1.c_str() + (s1.length() - 2), 3);
if (s1 != s2)
{
cout << " (6) I expected that \"" << s1 << "\" == \"" << s2 << "\"" << endl;
passed = 0;
}
if (!passed)
cout << "Failed appending char strings" << endl;
}
if (passed)
{
s1 = "";
s2 = "abcde ";
s1 << "abcde ";
if (s1 != s2)
passed = 0;
s1 << s1;
s2 += s2;
if (s1 != s2)
passed = 0;
s1 = "a";
s2 = "bc";
s1 << s2 << s2;
s2 = "abcbc";
if (s1 != s2)
passed = 0;
s1 = "";
short short1 = 1;
int i1 = 2;
long l1 = 3;
unsigned short short2 = 4;
unsigned int i2 = 5;
unsigned long l2 = 6;
s1 << short1 << short2 << i1 << i2 << l1 << l2;
s2 = "142536";
if (s1 != s2)
{
passed = 0;
cout << "failed streaming numbers, found \"" << s1 << "\" rather than \"" << s2 << "\"" << endl;
}
s2 += s2;
s1 << 1 << 4 << 25 << 36;
if (s1 != s2)
{
passed = 0;
cout << "failed streaming numbers(2), found \"" << s1 << "\" rather than \"" << s2 << "\"" << endl;
}
if (!passed)
cout << "Failed the streaming methods" << endl;
}
if (passed)
{
const char* strs[] = {
// string, wild, 0=nomatch
// "", "", "",
// "", "*", "",
// "", ".", "",
// "a", "", 0,
// "a", "a", "",
// "a", "a.", "",
// "a", "a..", 0,
// "a.", "a..", 0,
// "a.", "a.", "",
"hello", "*", "",
// "hello", "he*o", "",
// "hello", "he*", "",
// "hello", "*lo", "",
// "hello", "*h*e*l*l*o", "",
// "hello", "*h*e*l*l*o*", "",
// "hello", "*h*?*l*l*o", "",
// "hello", "***?*?*?**", "",
// "hello", "*h*e*l*l*o", "",
// "hello", "*.", "",
// "hello", "he*o.", "",
// "hello", "he*.", "",
// "hello", "*lo.", "",
// "hello", "*h*e*l*l*o.", "",
// "hello", "*h*e*l*l*o.*", 0,
// "hello", "*h*?*l*l*o.", "",
// "hello", "***?*?*?**.", "",
// "hello", "*h*e*l*l*o.", "",
// "hello.bat", "*.?a?", "",
// "hello.bat", "*.", 0,
0, 0, 0,
};
//static int fnmatch(const char* str, const char* wild, int case_senstive) const
for (int stri=0; strs[stri] != 0; stri += 3)
{
int rc = ADPString::fnmatch(strs[st
if (rc != 0 && strs[stri + 2] == 0 )
{
passed = 0;
cout << "\"" << strs[stri] << "\" matched \"" << strs[stri + 1] << "\" and it should not have" << endl;
}
else if (rc == 0 && strs[stri + 2] != 0 )
{
passed = 0;
cout << "\"" << strs[stri] << "\" did not match \"" << strs[stri + 1] << "\" and it should have" << endl;
}
}
}
return passed;
}
int main()
{
if (ADPString::test())
cout << endl << "ADPString::test() passed" << endl;
else
cout << endl << "ADPString::test() failed" << endl;
return 0;
}
#endif
Main Topics
Browse All Topics





by: prashant_n_mhatrePosted on 2002-11-06 at 11:26:05ID: 7416155
http://www.amberman.org/ev
http://www.cs.helsinki.fi/
http://www.aspire.cs.uah.e