home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 July / macformat-026.iso / mac / Shareware City / Developers / NString 1.0 beta / Sources / NString_Character.cxx < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-11  |  1.9 KB  |  68 lines  |  [TEXT/KAHL]

  1.  
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. #include "NString.h"
  6. #include "NString_Misc.h"
  7.  
  8. //_________________________________________________________________________________
  9.  
  10. char NString::operator[] (const unsigned long int k) const
  11. {
  12.     if ((k == 0) || (k > sb->len))
  13.         USAGE_ERR("operator[] (const unsigned long int)", "Attempted character read access in NString out of range");
  14.     return (sb->str[k-1]);
  15. }
  16.  
  17. //_________________________________________________________________________________
  18.  
  19. char NString::setchar (const unsigned long int k, const char c)
  20. {
  21.     const char *fname = "setchar (const unsigned long int, const char)";        // the method's name
  22.     char old;
  23.     
  24.     if ((k == 0) || (k > sb->len))
  25.         USAGE_ERR(fname, "Attempted character write access in NString out of range");
  26.     if (c == '\0')
  27.         USAGE_ERR(fname, "Attempted write of NUL character in NString");
  28.     if (sb->refs > 1)                            // the string body is used by another NString: must duplicate it to prevent
  29.         if (! DuplicateSB())                    //        changes in common body
  30.             OUT_OF_MEM(fname);
  31.     old = sb->str[k-1];
  32.     sb->str[k-1] = c;
  33.     return (old);
  34. }
  35.  
  36. //_________________________________________________________________________________
  37.  
  38. NString& NString::through(int (*action)(const char, const unsigned long int, NString&), direction_t dir)
  39. {
  40.     strbody *thru_sb = sb;
  41.     unsigned long int index;
  42.     int stop = 0;
  43.     
  44.     if (sb->len == 0)
  45.         return (*this);
  46.         
  47.     thru_sb->refs++;                                                            // the iterator is now looking at the string body
  48.     
  49.     if (dir == FORWARD)
  50.         for (index=1; (! stop) && (index <= thru_sb->len); index++)
  51.             stop = action(thru_sb->str[index-1], index, *this);
  52.     else
  53.         for (index=thru_sb->len; (! stop) && (index > 0); index--)
  54.             stop = action(thru_sb->str[index-1], index, *this);
  55.  
  56.     if ((--(thru_sb->refs)) == 0)                                        // the string body isn't used any longer -> must free it
  57.     {
  58.         free(thru_sb->str);
  59.         delete thru_sb;
  60.     }
  61.     
  62.     return (*this);
  63. }
  64.  
  65.  
  66.  
  67.  
  68.