Question

strings

Asked by: ronyjosf

Hi experts,

I work on windows OS, using msdev.

maybe you could help me on how to work with strings ( i don't use the string class though, i only can use char*, or char[] etc. )

for instance with operator = , when can i use '=' ? when do i have to use strcpy and so.

Thanks

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2002-11-06 at 10:27:30ID20391826
Topic

Miscellaneous Programming

Participating Experts
4
Points
35
Comments
4

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. strcpy and recursion
    Is there a way to write strcpy() as a recursion function without using any string library functions?
  2. Opening a file via MSDEV command line
    I want to be able to open a file in MSDEV using the command line, without getting a new MSDEV app instantiation. This attempt: "C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin\MSDEV.EXE" a.txt Opens a.txt in a new instantiation of MSDEV. I want it ...
  3. strcpy
    Hi experts, what did I do wrong in line00 and line01 ? It compiled but didn't run correctly ...thanks. -------------------------------------------- #include "stdafx.h" #include <iostream> #include <string> using namespace std; int m...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: pitonyakPosted on 2002-11-06 at 11:34:45ID: 7416185

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& aStream, char aDelimiter);
  istream& appendAToken(istream& aStream);
  istream& appendFile(istream& aStream) {return appendToDelimiter(aStream, '\0');}
  istream& appendLine(istream& aStream) {return appendToDelimiter(aStream, '\n');}

  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(const char* str, const char* wild, int case_senstive);

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 char* aString, int isCase, int num) :
    _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 std::string& aString, int isCase, int num) :
    _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 ADPString& aString, int isCase, int num) :
    _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 char* aString, int theLength)
{
  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 char* charPtr)
{
    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 ADPString& aString)
{
    setString(aString.c_str(), aString.length());
}


//**************************************************************************
//**                                                                      **
//**  Input : const ADPString& : String to assign                         **
//**                                                                      **
//**  Output: const ADPString& : reference to this                        **
//**                                                                      **
//**  Notes : Assignment operator                                         **
//**                                                                      **
//**************************************************************************

const ADPString& ADPString::operator=(const ADPString& aString)
{
    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 char* aString)
{
    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==(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< (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<=(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 : 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(const char* str) const
{
  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 c) const
{
  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(const ADPString& str) const
{
  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(const char* aStr)
{
    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 long x)
{
  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+=(const std::string& aString)
{
  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+=(const ADPString& aString)
{
   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+=(const char* aString)
{
    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 aChar)
{
    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(char aChar)
{
    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(istream& aStream, char aDelimiter)
{
    truncate(0);
    return appendToDelimiter(aStream, aDelimiter);
}


//**************************************************************************
//**                                                                      **
//**  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::appendToDelimiter(istream& aStream, char aDelimiter)
{
   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(), capacity()-length()-1, aDelimiter);
      _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(istream& aStream)
{
    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(istream& aStream)
{
   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(str.c_str(), wild.c_str(), case_sensitive);

        if (period_count > 1)
            return 0;

        ADPString temp_wild(wild);
        while (temp_wild.endsWith('*'))
            temp_wild.truncate(wild.length() - 1);

        if (temp_wild.endsWith('.'))
            temp_wild.truncate(wild.length() - 1);

        return fnmatch_no_periods_at_end(str.c_str(), temp_wild.c_str(), case_sensitive);
    }
    return fnmatch_no_periods_at_end(str.c_str(), wild.c_str(), case_sensitive);
}

int ADPString::fnmatch_no_periods_at_end(const char* str, const char* wild, int case_sensitive)
{
    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(str, wild, case_sensitive))
                    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 = "abcdefghijklmnopqrstuvwxyz";
    const char* alphaUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    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) || !s1.startsWith('a'))
        {
          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[stri + 0], strs[stri + 1], 0);
            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


 

by: VGRPosted on 2003-05-09 at 05:46:21ID: 8495034

Dear questionner/expert(s)

No comment has been added lately, so it's time to clean up this TA.
I'll leave a recommendation in the Cleanup topic area that this question is to be:

- Answered by: prashant_n_mhatre and pitonyak

Please leave any comments here within the next seven days.

==> PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER ! <==

VGR

Cleanup volunteer

 

by: SpideyModPosted on 2003-06-01 at 10:58:50ID: 8624592

Can't split a question where each expert would receive less than 20 points.  TO that end, I am selecting the first answer in.

SpideyMod
Community Support Moderator @Experts Exchange

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...