string.c

来自「开放源码的编译器open watcom 1.6.0版的源代码」· C语言 代码 · 共 698 行 · 第 1/2 页

C
698
字号


// resize -- Adjust the memory size of a string to accomodate some size
// Input:    CoolString object
// Output:   None

void CoolString::resize (long sz) {
#if ERROR_CHECKING
  if (sz < 0) {                         // If invalid size
    printf ("CoolString::resize(): Negative resize %d.\n", sz);
    exit (1);
  }
#endif
  char* temp = this->str;               // Save pointer to existing string
  this->size = sz+1;                    // Save size of allocated memory
  this->str = new char[sz+1];           // Allocate memory for desired size
  strcpy ((char *)this->str, temp);     // Copy original string back
  if (temp != Empty_String_g)
    delete temp;                        // Deallocate old memory
}


// operator<< -- Overload output operator for CoolString objects
// Input:        CoolString reference
// Output:       Formatted output and stream descriptor

ostream& operator<< (ostream& os, const CoolString& s) {
  return os << s.str;                           // Output char* and newline
}


// operator<< -- Overload output operator for string objects
// Input:        CoolString pointer
// Output:       Formatted output and stream descriptor

ostream& operator<< (ostream& os, const CoolString* s) {
  return operator<< (os, *s);
}


// strtol -- Returns as a long integer the value represented by the
//           CoolString pointer to by s, scanning upto the first character
//           that is inconsistent with the base. Leading white space is
//           ignored.
// Input:    Reference to CoolString object
//           Radix of number
// Output:   Long integer representing value contained in the CoolString

long strtol (const CoolString& s, char** ptr, int radix) {
  return (strtol ((char *)s.str, ptr, radix)); 
}       


// atol -- Equivalent to: strtol (str, (char**)END_OF_STRING, 10)
// Input:  Reference to CoolString object
// Output: Long integer representing value contained in the CoolString

long atol (const CoolString& s) {               // Convert string to long
  return (strtol ((char *)s.str, (char **) END_OF_STRING, int(10)));
}


// atoi -- Equivalent to: (int)strtol (str, (char**)END_OF_STRING, 10)
// Input:  Reference to CoolString object
// Output: Integer representing value contained in the CoolString

int atoi (const CoolString& s) {                // Convert string to int
  return int(strtol ((char *)s.str, (char **) END_OF_STRING, int(10))); 
}


// strtod -- Returns as a double-precision floating-point number the
//           value represented by a CoolString object. Characters are
//           scanned upto the first unrecognized character.
// Input:    Reference to CoolString object
// Output:   Double representing value contained in CoolString

double strtod (const CoolString& s, char** ptr) {       // Convert string to double
  return (strtod ((char *)s.str, ptr));
}


// trim -- Removes any occurrence of the character(s) in "c" from "s"
// Input:  Simople_CoolString reference, character string
// Output: Modified CoolString "s" object

CoolString& trim (CoolString& sr, const char* rem) {
  char* s = sr.str;
  char* result = sr.str;
  long len = 0;
  register char c;
  while ((c=*s++) != END_OF_STRING) {
    register const char* r = rem;
    register char t;
    while ((t=*r++) != END_OF_STRING && t != c); // Scan for match
    if (t == END_OF_STRING)                      // If no match found
      *result++ = c, len++;
  }
  *result = END_OF_STRING;                      // NULL terminate string
  sr.length = len;
  return sr;                                    // Return string
}


// left_trim -- Removes any occurrence of the character(s) in "c" from
//              "s" that appear as a prefix to the string. The first
//              non-matching character encountered terminates the remove
//              operation and the rest of the string is copied intact.
// Input:       CoolString reference, character string
// Output:      Modified CoolString "s" object

CoolString& left_trim (CoolString& sr, const char* rem) { // Trim prefix from CoolString
  char* result = sr.str;
  char* s = sr.str;
  long len = 0;
  register char c;
  for (; (c=*s) != END_OF_STRING; s++) {
    register const char* r = rem;
    register char t;
    while ((t=*r++) != END_OF_STRING && t != c); // Scan for match
    if (t == END_OF_STRING)                      // If no match found
      break;
  }
  if (s != result)                                // when characters trimed
    while ((*result++ = *s++) != END_OF_STRING) len++; // shift string down
  sr.length = len;
  return sr;                            // Return string reference
}


// right_trim -- Removes any occurrence of the character(s) in "c" from
//               "s" that appear as a suffix to the string. The first
//               non-matching character encountered terminates the remove
//               operation and the rest of the string is copied intact.
// Input:        CoolString reference, character string
// Output:       Modified CoolString "s" object

CoolString& right_trim (CoolString& sr, const char* rem) {
  char* str = sr.str;
  char* s = str + strlen(str) - 1;              // last character of string
  for (; s >= str; s--) {
    register const char* r = rem;
    register char t;
    register char c = *s;
    while ((t=*r++) != END_OF_STRING && t != c); // Scan for match
    if (t == END_OF_STRING)                      // If no match found
      break;
  }
  *(s+1) = END_OF_STRING;
  sr.length = s - str;
  return sr;                            // Return CoolString reference
}


// upcase -- Convert all alphabetical characters to uppercase
// Input:    CoolString reference
// Output:   Updated string

CoolString& upcase (CoolString& s) {    // Convert entire string to upper case
  c_upcase(s.str);
  return s;                     // Return reference to modified string
}


// downcase -- Convert all alphabetical characters to lowercase
// Input:      CoolString reference
// Output:     Updated string

CoolString& downcase (CoolString& s) {  // Convert entire string to lower case
  c_downcase(s.str);
  return s;                     // Return reference to modified string
}

// capitalize -- Capitalize all words in a CoolString. A word is define as
//               a sequence of characters separated by non alphanumerics
// Input:        CoolString reference
// Output:       Updated string

CoolString& capitalize (CoolString& s) {        // Capitalize each word in string
  c_capitalize(s.str);
  return s;                     // Return reference to modified string
}


// insert -- Insert a char* at the position specified by start.
// Input  -- A char* to be inserted and a long index.          
// Output -- A Boolean, true if insertion took place, false if error.

Boolean CoolString::insert (const char* ins, long start) {
  if (start<0 || start>this->length) return(FALSE);  // Boundary check
  long len=strlen(ins);                 // length of char*
  this->length += len;                  // Determine length of new string
  if (this->size <= this->length)       // If not enough allocated memory
    update_memory (*this);              // Adjust/update memory if necessary
  register char* ptr = this->str;
  register char* st = ptr + start;
  register char* end = ptr + this->length;
  for (ptr = end - len; ptr >= st;)             // Make space for ins
    *end-- = *ptr--;
  for (end = st+len; st < end; *st++ = *ins++); // Insert ins into that
  return(TRUE);                         // Insert worked
}


// remove -- Removes everything between the start and end indexes of string
//           The character at start is removed and all characters up to but 
//           not including the character at end.
// Input  -- A start and end index into the string.
// Output -- A Boolean, true if remove worked, false if error.

Boolean CoolString::remove (long start, long end) {
  if (start<0 || start > this->length || end<0  // Boundary check
      || end > this->length || end<=start)
    return(FALSE);                              // Out of bounds, failure
  this->length -= (end-start);                  // New (shorter) length
  for(; this->str[start]=this->str[end]; start++) end++; // Remove everything
  return(TRUE);                                 // Remove worked
}


// replace -- Removes everything between start and end as in remove(), and
//            inserts the char* argument into the place of what was removed.
// Input   -- A start and end for remove and a char*, c, to insert.
// Output  -- A Boolean, true if replace worked, false if error.

Boolean CoolString::replace (const char* c, long start, long end) {
  if (start<0 || start > this->length || end<0  // Boundary check
      || end > this->length || end<=start)      // out of bounds, failure
    return(FALSE); 
  long len=strlen(c);                   // length of c
  long delta = len - end + start;       // find overall change in length
  this->length += delta;                // set new length
  if (this->size <= this->length)       // If not enough allocated memory
    update_memory (*this);              // Adjust/update memory if necessary
  long ind;
  if (delta > 0) {                                // If replacement is bigger
    for (ind=this->length; start+len<=ind; ind--) // than chacters replaced
      this->str[ind] = this->str[ind-delta];
  }
  else if (delta < 0) {                 // Replacement is shorter
    char* st = this->str + start + len;
    char* ptr = this->str + end;
    char* end = this->str + this->length;
    while (st<=end) *st++ = *ptr++;
  }
  { char* ptr = this->str+start;
    char ch;
    while ((ch = *c++) != END_OF_STRING) // replace characters
      *ptr++ = ch;
  }
  return(TRUE);
}


// yank   -- Removes everything between start and end, copies it into a 
//           a string and returns that string.
// Input  -- A reference to a CoolString.  A start and end for the remove.
// Output -- none.  Sets the CoolString.

void CoolString::yank (CoolString& s, long start, long end) {
#if ERROR_CHECKING
  if (start < 0 || start > this->length || end < 0      // Boundary check
      || end > this->length || end <= start) {
    printf ("CoolString::sub_yank(): Start %d and/or end %d index invalid.\n",
            start, end);
    exit (1);
  }
#endif
  long len = end - start;
  strncpy(s, this->str+start, len);     // Copy stuff to yank into s
  this->length -= len;                  // set new length
  for(; this->str[start]=this->str[end]; start++) end++;  // Do the remove
}


// sub_string -- Returns a new string initialized to what is between the
//               start and end indexes.
// Input      -- A reference to a String.  Two longs, a start and an end
// Output     -- none.  Sets the CoolString.

void CoolString::sub_string (CoolString& s, long start, long end) {
#if ERROR_CHECKING
  if (start < 0 || start > this->length || end < 0      // Boundary check
      || end > this->length || end <= start) {
    printf ("CoolString::sub_string(): Start %d and/or end %d index invalid.\n",
            start, end);
    exit (1);
  }
#endif
  strncpy(s, this->str+start, end - start);     // Copy substring into s
}


// strncpy -- Returns s, with the first length characters of source copied
//            into it.  The old value of s is lost.
// Input   -- A reference to a CoolString s, a char* source, and a long length.
// Output  -- The modified CoolString s.

CoolString& strncpy(CoolString& s, const char* source, long length) {
#if ERROR_CHECKING
  if (length < 0) {                     // Boundary check
    printf ("CoolString::strncpy(): Negative length %d.\n", length);
    exit (1);
  }
#endif
  s.length = length;                    // Set new string length
  if (s.size <= length) {               // If not enough allocated memory
    if (s.str && s.str != Empty_String_g)
        *s.str = END_OF_STRING;         // Don't copy old string
    update_memory (s);                  // Adjust/update memory if necessary
  }
  char* p = s.str;
  while (length-- > 0)                  // Copy source into string
    *p++ = *source++;
  *p = END_OF_STRING;                   // set the end byte
  return s;
}


// bracket_error -- Raise exception for operator[]
// Input:           Index value
// Output:          None

void CoolString::bracket_error (long n) {
  printf ("CoolString::operator[](): Index %d out of range.\n", n);
  exit (1);
}


// growth_error -- Raise exception for set_alloc_size()
// Input:          Growth value
// Output:         None

void CoolString::growth_error (int i) {
  printf ("CoolString::set_alloc_size(): Negative growth size %d.\n", i);
  exit (1);
}

// ratio_error -- Raise exception for set_growth_ratio()
// Input:         Growth ration
// Output:        None

void CoolString::ratio_error (float ratio) {
  printf ("CoolString::set_growth_ratio(): Negative growth ratio %f.\n", ratio);
  exit (1);
}

int CoolString::alloc_size_s = 0;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?