A String Library

A short overview of a string library contained in jlib.lib - created by John Findlay

library version 1.03

Current list and bookmarks for library functions:

str_add str_delete_all str_fputs str_int str_msgbox str_rev
str_arrptr str_dup str_fread str_isequal str_new str_rinstr
str_buflen str_extract str_fwrite str_isequali str_print str_search
str_clean str_extractfile str_getid str_isstring str_printc str_searchi
str_cmp str_extractpath str_hash str_lasterror str_printf str_set
str_cmpi str_fgets str_hashget str_len str_qsort str_tab_to_space
str_copy str_float str_idreap str_libvers str_qsorti str_token
str_count str_format str_insert str_locate str_remspace str_to_char
str_delete str_fprint str_instr str_locatei str_resize str_upper
str_lower str_xlate

Introduction:

For the purpose of this description a 'string' denotes an object of type STRING as distinct from an array of chars. This string library functions maintain a STRING object for use specifically by the LCC-Win32 C compiler. The library facilitates dynamic allocation and resizing of these string objects as required and 'overloading' is used to call various functions with different parameter types.

The string object's array of chars are zero based - so for example, functions returning a character position will return '0' or greater for the position and not the address of the character.

The library maintains a count of how many string objects have been allocated and stores all current object's pointers and ID's. The id's are zero based; when an object somewhere in the index is deleted all objects above that index are moved up one and their id's are adjusted to reflect their new position in the index. This may be a novel feature but allows the user to access any indexed string object. Also when deleting objects one can check that all objects have been de-allocated before exiting by checking the object count.

Each string object also has storage for a hash value - this value will not be generated unless the function str_hash() is called for a particular valid string object. Subsequently this value can be retrieved with a call to str_hashget().

Many of the library functions use the LCC-Win32 'overloaded' extension. This means that one can call the same function using different types. For example:

int str_extractfile( STRING * restrict dest, const STRING * restrict src );
int str_extractfile( STRING * restrict dest, const char * src );

Selecting Ansi-C only from LCC-Win32's projects configuration dialog will cause compilations errors as the 'overloaded' feature is an extension to the langauge and not part of Ansi-C.


Cautionary note: a STRING is a pointer to a string object and like other pointers cannot be used until it has been initialised. If an un-initialised string object is passed to any function other than str_new() undefined behaviour is the result.

You must always start by creating a new string object before any work can be done.

Example:

STRING mystr = str_new(80);

or

STRING mystr;
mystr = str_new(80);

This will create a string object containing an array of 80 chars.

or for an array of string objects:

STRING s[4];
for (int i =0; i<4; i++){
    s[i] = str_new( 80 );
}

When allocating or resizing strings, the maximum length is limited to INT_MAX (0x7FFFFFFF - 2147483647), hopefully you will not require strings larger than that.

Any pointers to char arrays (char*) passed to string library functions are expected to be pointing to a NULL terminated char array - undefined behaviour results otherwise.


I will explain a few examples, then the syntax of each function will be listed and described.

All strings start life with a call to str_new which creates a new string object with a specified size for the array of chars.

The syntax for str_new:

    STRING str_new( int buf_len );
    STRING str_new( const char * src );
 
The abstract Type named STRING is defined in str.h. STRING is actually a pointer to Type.

Examples:

    STRING s1 = str_new( 100 );

    STRING s1 = str_new( "A quick brown fox" );

If the new string has been successfully created 's1' will now point to the new object. If for some reason str_new failed it will return a NULL pointer. The default or minimum size is 20 bytes for the array of chars, so if requested length is smaller than 20, the size will automatically be made to 20 bytes/chars.

To assign characters to the previously created string object one can use str_copy.

    int str_copy( STRING restrict dest, const STRING * restrict src );
    int str_copy( STRING restrict dest, const char * c );

The function str_copy will assign either a another string object 'src', a string literal or char array to the previously created object 'dest'.

Examples:

   char str[] = "The quick brown fox";
   STRING s1 = str_new( 10 );
   STRING s2 = str_new( 10 );
 
   str_copy( s1, str); // case 1
   str_copy( s1, "The quick brown fox" ); // case 2
   str_copy( s2, s1 ); // case 3

In all cases, if the size of the destination string object is not large enough to accommodate all the chars from the source the size will be adjusted accordingly. All strings objects will be terminated with a null byte as is normal for C.

After one has finished using the object it should be deleted, this deletion should occur of course while your variable (string object) is still in-scope. The function str_delete is used for this purpose.

    { // start scope

        STRING s1 = str_new( 0 );
        // do something
        str_delete( s1 );

    } // end scope

The function str_delete frees the memory allocated for the array of chars and the string object itself. Do not use the string object after it has been deleted.

A few final words before moving on to the description of each function in the string library. String resizing is upward only, you cannot shrink the array of chars by normal operations. However, one function can effectively do this by deleting the present array of chars and starting again. The function is str_clean.

Consider the case where you have used a certain string object for many operations, perhaps dealing with a few large arrays. Copying from one object to another causes the destination string object to be sized to the largest needed for any of those operations. So the string object could now have a large array of chars that may not be necessary for future use. The function str_clean will take the string object back to a pristine condition just as if it had been newly created with the default size of 20 chars. Of course, any data contained in the original array of chars will be lost.

Most functions either return a success integer or a error code that will be -ve. These error codes are defined in str.h.

However, for some functions returning an error code is not appropriate; str_new for instance returns a pointer to the new object but if an error occurs a NULL pointer is returned and the function will set a string library variable that can be retreived by calling str_lasterror(). The error should be retrieved before any other library call is made as it may be over-written by the next call to the library.

The functions str_new(), str_dup() and str_to_char() return pointers if successful or NULL if failed.

Normal error checking can be done thus for library functions that retrun an integer:

if ( str_xxx() < 0 ){
    then error
}

At this time the library maintains a maximum number of string objects of 10000. This could be made open ended in future versions.

The syntax and explanation of each function


str_add: (overloaded)

syntax:

int str_add( STRING restrict dest, const STRING restrict src );
int str_add( STRING restrict dest, const char * c );

str_add will concatenate object 'src' with object 'dest' or array of char 'c' with object 'dest' adjusting the storage space accordingly.

Return values:

If the function succeeds the number of chars concatenated to object 'dest' will be returned. If memory reallocation fails STRERR_MEMORY will be retruned.


str_arrptr: (array pointer)

syntax:

char * str_arrptr( STRING restrict s );

Sometimes it is necessary to pass a pointer of the string object's char array to another function such as a Windows API.

str_arrptr returns the address of the first character of the array.

Example:

SetWindowText(hwnd, str_arrptr(mystr));

or

GetWindowText(hwnd, str_arrptr(mystr), str_buflen(mystr) );


str_buflen:

syntax:

int str_buflen( const STRING restrict s );

str_buflen returns the total size of the string object's buffer. This may be considerably larger than the NULL terminated array of chars held by the object. See str_len().


str_instr:

syntax:

int str_instr( STRING restrict s, const char c, int pos );

str_instr will search for the occurence of character 'c' in the string object 's' starting from position 'pos'.

Returns the zero based position of character 'c' in object 's' or STRERR_NOTFOUND.

If 'pos' is greater than the length of object 's' the return will be STRERR_SIZE.


str_rinstr:

syntax:

int str_rinstr( STRING restrict s, const char c, int pos );

str_rinstr will search for the occurence of character 'c' in the string object 's' in reverse order starting from 'pos'.

Returns the zero based position of character 'c' in object 's' or STRERR_NOTFOUND.

If 'pos' is greater than the length of object 's' the return will be STRERR_SIZE.


str_search: (overloaded)

syntax:

BOOL str_search( const STRING restrict pattern, int * index, int * pos );
BOOL str_search( const char * pattern, int * index, int * pos );
 
str_search uses the string libraries internally stored ID's of the string objects to search for a case sensitive match of 'pattern'.
 
This function would normally be used when the string objects are initialised as an array of objects.
 
The function will search through all string objects for the occurrence of sub string object 'pattern' or array of chars 'pattern'. The search starts at id 'index' and position 'pos' of that object and continues until the match is found or the last allocated string id has been searched.
 
The variables 'index' and 'pos' are passed as pointers to 'int' so set these two vars before calling str_search().

Example:

int pos = 3, index = 3;
if ( str_search( "popo", &index, &pos ) ){
str_printf( str_idreap(index), " Index - %d Position - %d\n", index, pos);
}else{
str_printc( "Not found!" );
}

Returns values:

str_search returns Boolean TRUE if the search was successful and FALSE if not.

The variable 'index' will contain the id and variable 'pos' will contain the start position in the string object if a match for 'pattern' is found.

If 'pos' is greater than the length of the first string object in the list of ID's, searching will start at index+1.


str_searchi: (overloaded)

syntax:

BOOL str_searchi( const STRING restrict pattern, int * index, int * pos );
BOOL str_searchi( const char * pattern, int * index, int * pos );
 
str_searchi uses the string libraries internally stored ID's of the string objects to search for a case in-sensitive match of 'pattern'.
 
This function would normally be used when the string objects are initialised as an array of objects.
 
The function will search through all string objects for the occurrence of sub string object 'pattern' or array of chars 'pattern'. The search starts at id 'index' and position 'pos' and continues until the match is found or the last allocated string id has been searched.
 
The variables 'index' and 'pos' are passed as pointers to 'int' so set these two vars before calling str_searchi().

Example:

int pos = 3, index = 3;
if ( str_searchi( "POPO", &index, &pos ) ){
str_printf( str_idreap(index), " Index - %d Position - %d\n", index, pos);
}else{
str_printc( "Not found!" );
}

Returns values:

str_searchi returns Boolean TRUE if the search was successful and FALSE if not.

The variable 'index' will contain the id and variable 'pos' will contain the start position in the string object if a match for 'pattern' is found.

If 'pos' is greater than the length of the first string object in the list of ID's, searching will start at index+1.


str_set:

syntax:

STRING str_set( STRING restrict s, const char c );

str_set sets all characters in string object 's' to a given character 'c'. Operation stops when the null termination is found. This operation is carried out in-situ, all previous characters are lost.

Returns the pointer to object 's' allowing the function to be used as a parameter in another function.


str_tab_to_space:

syntax:

int str_tab_to_space( STRING restrict s, int numspaces );

str_tab_to_space replaces all occurrences of the tab character in string object 's' with a specified number of spaces, 'numspaces'. The string object 's' is resized to accomadate the extra characters.

Return values:

If successful returns the number of tabs converted to spaces, if failed returns zero. Failure will be either no tabs were found or extra memory could not be allocated. Use str_lasterror().


str_clean:

syntax:

int str_clean( STRING restrict s );

str_clean will take the string object back to a pristine condition just as if it had been newly created with the default size of 20 chars. Any characters stored will be lost and hash value will be set to '0'. The original ID will still be valid.

Return values:

If successful returns STRERR_NONE, if failed returns STRERR_MEMORY.


str_cmp: (overloaded)

syntax:

int str_cmp( const STRING restrict s1, const STRING restrict s2 );
int str_cmp( const STRING restrict s1, const char * c );

str_cmp does a case sensitive comparison between string objects 's1' and 's2' or between string object 's1' and array of chars 'c'.

Return values are as follows:

if 's1' < 's2' returns < 0
if 's1' > 's2' returns > 0
if 's1' == 's2' returns 0

if 's1' < 'c' returns < 0
if 's1' > 'c' returns > 0
if 's1' == 'c' returns 0


str_cmpi: (overloaded)

syntax:

int str_cmpi( const STRING restrict s1, const STRING restrict s2 );
int str_cmpi( const STRING restrict s1, const char * c );

str_cmpi does a case in-sensitive comparison between string objects 's1' and 's2' or between string object 's1' and array of chars 'c'.

Return values are as follows:

if 's1' < 's2' returns < 0
if 's1' > 's2' returns > 0
if 's1' == 's2' returns 0

if 's1' < 'c' returns < 0
if 's1' > 'c' returns > 0
if 's1' == 'c' returns 0


str_copy: (overloaded)

syntax:

int str_copy( STRING restrict dest, const STRING restrict src );
int str_copy( STRING restrict dest, const char * c );

str_copy will copy the contents of object 'src' to object 'dest' or the array of chars 'c' to object 'dest'. The result will be that object 'dest' contains the new array of chars from either 'src' or 'c' including the null terminator.

Adjustment of storage will be undertaken if size of 'src' is greater than size of 'dest'.

Return values:

If successful the number of copied chars. If memory reallocation fails the error code STRERR_MEMORY will be returned.


str_count:

syntax:

int str_count();

str_count returns the total number of string objects that are current. Useful during development to check for memory leaks. All objects that have been deleted are not included in this count.

Return value:

The number of created string objects that are current. If the number of objects allocated is zero, the function will return 0.


str_delete:

syntax:

void str_delete( STRING restrict s );

str_delete will free all memory associated with the object 's'. You should delete in-scope and not use the object's pointer again after using str_delete.

The string library maintains an internal array that stores all string objects up to a maximum of 10000 - after using str_delete, the pointers above the deleted object are moved down one, also the id of these moved objects will be decremented by 1 resulting in contiguous id's in the index when deleting individual objects.


str_delete_all:

syntax:

void str_delete_all( void );

str_delete_all will free all string objects. Do not use any previously created string object after calling this function. Useful when app terminates!!


str_dup:

syntax:

STRING str_dup( STRING restrict src );

This creates a new STRING object.

str_dup will duplicate string object 'src'. The function will create a new string object that has a string length the same as the object 'src' up to the NULL terminator, not the buffer length of 'src'. The newly created string object acquires a new ID value but the hash value will be copied if the original string object has one.

Example:

if ( NULL == ( newstring = str_dup( mystring )) ){
then error
}

Return values:

If successful a valid pointer to the new string object will be returned. If the function fails the function will return a NULL pointer. Use str_lasterror() to retrieve the error code. Either STRERR_MAXALLOCAT when string allocation has exceeded maximum allowed, or STRERR_MEMORY if memory allocation failed.


str_extract: (overloaded)

syntax:

int str_extract( STRING restrict dest, const STRING restrict src, int pos, int nlen );
int str_extract( STRING restrict dest, const char * c , int pos, int nlen );

This function extracts characters from the string object 'src' or array of chars 'c' starting at 'pos' for a length of 'nlen' and places them into string object 'dest'. If 'dest' is not large enough to accommodate the characters, 'dest' will be resized.

Return values:

On success the number of copied chars will be returned.

If 'nlen' + 'pos' is larger than the size of object 'src' or array of chars 'c' the operation will be aborted and STRERR_SIZE will be returned. If resizing 'dest' fails STRERR_MEMORY will be returned.


str_extractfile: (overloaded)

syntax:

int str_extractfile( STRING restrict dest, const STRING restrict src );
int str_extractfile( STRING restrict dest, const char * src );

Given the full path and file name in string object 'src' str_extractfile will extract the file name and copy it to object 'dest'.

Return values:

If the file name is found the function returns the number of chars copied to object 'dest'. If no path delimiters are found, returns zero and if memory reallocation fails returns STRERR_MEMORY. In the unlikely event that the file name is longer than MAX_PATH the function will return STRERR_SIZE.


str_extractpath: (overloaded)

syntax:

int str_extractpath( STRING restrict dest, const STRING restrict src );
int str_extractpath( STRING restrict dest, const char src );

Given the full path and file name in string object 'src' str_extractpath will extract the path name and copy it to object 'dest'.

Return values:

If the path is found the function retruns the number of chars copied to object 'dest'.

If no path delimiters are found, returns zero and if memory reallocation fails returns STRERR_MEMORY. In the unlikely event that the path name is longer than MAX_PATH the function will return STRERR_SIZE.


str_fgets:

syntax:

int str_fgets( FILE * stream, STRING restrict s, int n );

str_fgets reads characters from the 'stream' into the string object 's'. The function stops reading when it reads either 'n' - 1 characters or a newline character whichever comes first. str_fgets retains the newline character at the end of object 's'. A null byte is appended to s to mark the end of the string.

Return Value:

On success str_fgets returns the number of characters read into object 's'; it returns NULL on end-of-file or error and str_lasterror will return STRERR_READ.


str_float:

syntax:

int str_float( STRING restrict s, const double f );

str_float makes a string representation of floating point 'f' value and places it in object 's'. Positive and negative values are represented. Adjustment of storage will be undertaken if size of string object 's' is not large enough.

Return values:

If the function succeeds the number of chars copied to object 's' will be returned. If memory reallocation fails STRERR_MEMORY will be retruned.


str_format:

syntax:

int str_format( STRING restrict s, char * format, ... );

General purpose string formatting is performed by str_format. str_format takes a variable number of arguments, the result will be stored in object 's'.

Returns number of copied chars if successful, otherwise zero on error. A format specification has the same specification as printf():

Format specifications

A format specification, which consists of optional and required fields, has the following form:

%[flags] [width] [.precision] [{h | l | L}]type

Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character (for example, %s). If a percent sign is followed by a character that has no meaning as a format field, the character is copied to stdout. For example, to print a percent-sign character, use %%.

The optional fields, which appear before the type character, control other aspects of the formatting, as follows:

type Required character that determines whether the associated argument is interpreted as a character, a string, or a number (see the Type table).

flags Optional character or characters that control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes (see Flags table). More than one flag can appear in a format specification.

width Optional number that specifies the minimum number of characters output.

The width argument is a nonnegative decimal integer controlling the minimum number of characters printed. If the number of characters in the output value is less than the specified width, blanks are added to the left or the right of the values depending on whether the flag (for left alignment) is specified until the minimum width is reached. If width is prefixed with 0, zeros are added until the minimum width is reached (not useful for left-aligned numbers).

The width specification never causes a value to be truncated. If the number of characters in the output value is greater than the specified width, or if width is not given, all characters of the value are printed (subject to the precision specification).

If the width specification is an asterisk (*), an int argument from the argument list supplies the value. The width argument must precede the value being formatted in the argument list. A nonexistent or small field width does not cause the truncation of a field; if the result of a conversion is wider than the field width, the field expands to contain the conversion result.

precision Optional number that specifies the maximum number of characters printed for all or part of the output field, or the minimum number of digits printed for integer values (see the Precision table)

h | l | L Optional prefixes to type - that specify the size of argument.

Adjustment of storage will be undertaken if size of the string to copy to object 's' is greater than size of 's'. Returns number of copied chars if successful, otherwise zero. Use str_lasterror() to retrieve error code.

Printf type specifications table

Char Type Output
     
c int or wint_t When used with printf functions, specifies a single-byte character
d int Signed decimal integer
I int Signed decimal integer
o int Signed octal integer
u int Unsigned decimal integer
x int Unsigned hexadecimal, using a, b, c, d, e and f
X int Unsigned hexadecimal, using A, B, C, D, E and F
    For all long long integers prefix with 'L' i.e. %Ld
e double Signed value having the form []d.dddd e [sign]ddd where d is single decimal digit, dddd is one or more decimal digits, ddd is exactly three decimal digits, and sign is + or -
E double Identical to the previous format, only that the exponent will be written E and not e.
f double Signed value having the form [ ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
g double Signed value having the form [ ]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
G double The same as the previous one, only that the exponent will be written as E for exponent if e format used.
    For all long double types prefix with 'L' i.e. %Lg
n Pointer to integer Number of characters successfully written so far to the stream or buffer; this value is stored in the integer whose address is given as the argument.
p Pointer to void Prints the address pointed to by the argument in the form xxxx:yyyy where xxxx is the segment and yyyy is the offset, and the digits x and y are uppercase hexadecimal digits.
s String pointer Prints characters until a null-terminator is encountered or precision value is reached.
S String pointer Prints characters until a null-terminator is encountered or precision value is reached.

Printf flags table

Flag Meaning Default
     
- Left align the result within the given field width default
+ Prefix the output value with a sign (+ or ) if the output value is of a signed type. Sign appears only for negative signed values
0 If width is prefixed with 0, zeros are added until the minimum width is reached. If 0 and appear, the 0 is ignored. If 0 is specified with an integer format (i, u, x, X, o, d) the 0 is ignored.    None
blank Prefix the output value with a blank if the output value is signed and positive; the blank is ignored if both the blank and + flags appear No blank appears.
# When used with the o, x, or X format, the # flag prefixes any nonzero output value with 0, 0x, or 0X, respectively No blank appears
# When used with the e, E, or f format, the # flag forces the output value to contain a decimal point in all cases No blank appears
# When used with the g or G format, the # flag forces the output value to contain a decimal point in all cases and prevents the truncation of trailing zeros. Ignored when used with c, d, i, u, or s. Decimal point appears only if digits follow it. Trailing zeros are truncated.

Printf precision table

Type Meaning Default
     
c, C The precision has no effect. Character is printed
d, i, u, o, x, X The precision specifies the minimum number of digits to be printed. If the number of digits in the argument is less than precision, the output value is padded on the left with zeros. The value is not truncated when the number of digits exceeds precision. Default precision is 1.
e, E The precision specifies the number of digits to be printed after the decimal point. The last printed digit is rounded.  Default precision is 6; if precision is 0 or the period (.) appears without a number following it, no decimal point is printed
f The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits. Default precision is 6; if precision is 0, or if the period (.) appears without a number following it, no decimal point is printed.
g, G The precision specifies the maximum number of significant digits printed. Six significant digits are printed, with any trailing zeros truncated.
s, S The precision specifies the maximum number of characters to be printed.  Characters in excess of precision are not printed. Characters are printed until a null character is encountered.

 


str_fprint:

syntax:

int str_fprint( FILE *stream, const STRING restrict s, BOOL nl = TRUE )

str_fprint sends the string of object 's' to the previously open file stream. Use 'nl' to determine if a new line
character is appended. TRUE means that a new line will be appened, FALSE means a new line character will not be appended.

The 'nl' parametr defaults to TRUE so without suppling an argument it will print with a new line character appended. Examples;

str_fprint( stream, mystr ); // this will print 'mystr' and a new line char.

str_fprint( stream, mystr, FALSE ); // this will not print a new line char.

The function returns the number of chars output. In the event of error it returns EOF and str_lasterror will retrun STRERR_WRITE.


str_fputs:

syntax:

int str_fputs( FILE *stream, const STRING restrict s )

str_fputs sends the string of object 's' to the previously open file stream; it does not append a newline character and the terminating null character is not copied.

Return Value;

On success str_fputs returns a non-negative value. On error it returns a value of EOF (-1) and str_lasterror will retrun STRERR_WRITE.


str_fread:

syntax:

int str_fread( FILE *stream, STRING restrict dest, int size );

str_fread reads 'size' bytes from the file stream, placeing the result in string object 'dest'. Resizeing will occur if 'dest' is not large enough to hold the data.

Return value:

On successful completion str_fread returns the number of bytes actually read. On error the retrun will be less than the number of bytes requested possibly caused by the end of file. str_lasterror() will return STRERR_READ if operation was not successful.


str_fwrite:

syntax:

int str_fwrite( FILE *stream, STRING restrict src, int size );

str_fwrite writes string object 'src' to a stream and appends 'size' bytes to the given output file 'stream'.

Return value:

On successful completion str_fwrite returns the number of bytes actually written. On error the retrun will be less than the number of bytes requested to be written. str_lasterror() will return STRERR_READ if operation was not successful.


str_getid:

syntax:

int str_getid( const STRING restrict s );

str_getid retrieves the identifier of the object 's'. See introduction.


str_hash: (overloaded)

syntax:

unsigned long str_hash( const STRING restrict src );
unsigned long str_hash( const char * restrict src );

str_hash generates a hash value for the string object or array of chars 'src'. The hash function is based on the Cyclic Redundancy Check with a 32 bit algorithm as invented by Mark Adler.

When using hash values it is important to remember that a hash value is not generated automatically. If the contents of the string object has changed you will need to call str_hash() again, otherwise you will have an invalid hash value for the current string.

Return value:

str_hash returns an unsigned long value on success, zero on failure


str_hashget:

syntax:

unsigned long str_hashget( const STRING restrict src );

str_hashget retrieves the hash value previously generated with str_hash. If no previous value has been generated the function returns zero.


str_idreap:

syntax:

STRING str_idreap( int id );

str_idreap retrieves the string object from the identifier 'id'.

This creates a new STRING object.

Example:

id = str_count();
STRING hcpy = str_idreap( id );

The new string object 'hcpy' will point to the last string created.

Rerturn value:

If successful returns the pointer to the object identified by id. If id is greater than the number of created string objects the function will return NULL and str_lasterror() will retrun STRERR_SIZE.


str_insert: (overloaded)

syntax:

int str_insert( STRING restrict dest, const STRING restrict src, int pos, nt nlen );
int str_insert( STRING restrict dest, const char * c, int pos, nt nlen );

str_insert will insert object 'src' into object 'dest' or array of char 'c' into object 'dest' starting at position 'pos' and copying 'nlen' number of characters. Storage will be adjusted if the total size required is greater than the size of 'dest'. If final length is greater than original string a null terminator will be added, if not greater than original string, there will be no null terminator added.

Return values:

If successful the function returns the number of chars inserted into object 'dest'. If memory reallocation fails STRERR_MEMORY will be returned.


str_int:

syntax:

int str_int( STRING restrict s, int i );

str_int makes a string representation of integer 'i' and places it in object 's'. Positive and negative values are represented. Returns the number of characters copied to object 's'.

Adjustment of storage will be undertaken if size of the string to copy to object 's' is greater than size of 's'.

Return values:

If the function succeeds the number of chars copied to object 's' will be returned. If memory reallocation fails STRERR_MEMORY will be retruned.


str_isequal: (overloaded)

syntax:

BOOL str_isequal( const STRING restrict s1, const STRING restrict s2 );
BOOL str_isequal( const STRING restrict s1, const char * c );
str_isequal compares the two strings and returns TRUE if the two strings match, returns FALSE if not. This comparison is case sensitive.

str_isequali: (overloaded)

syntax:

BOOL str_isequali( const STRING restrict s1, const STRING restrict s2 );
BOOL str_isequali( const STRING restrict s1, const char * c );
str_isequali compares the two strings and returns TRUE if the two strings match, returns FALSE if not. This comparison is not case sensitive.

str_isstring:

syntax:

BOOL str_isstring( STRING This );

str_isstring checks the validity of the STRING object 'This'. If the STRING is valid returns TRUE, otherwise retruns FALSE.


str_lasterror:

syntax:

int str_lasterror();

str_lasterror returns the last error recorded by the library. An error needs to be retrieved immediately after the call that generated the error because subsequent calls to the library may clear this error.

Errors are defined in str.h and are:

#define STRERR_NONE 0
#define STRERR_MEMORY -1
#define STRERR_SIZE -2
#define STRERR_NOTFOUND -3
#define STRERR_MAXALLOCAT -4
#define STRERR_WRONGARGS -5
#define STRERR_NOSTRING -6
#define STRERR_READ -7
#define STRERR_WRITE -8

str_len:

syntax:

int str_len( const STRING restrict s );

str_len returns the length of the string up to the null terminator.


str_libvers:

syntax:

void str_libvers( void );

Displays a MessageBox showing which library version is in use.


str_locate: (overloaded)

syntax:

int str_locate(const STRING restrict s1, const STRING restrict s2 );
int str_locate(const STRING restrict s1, const char * c );

str_locate searches through object 's1' trying to find the same pattern of characters from object 's2' or array of chars * 'c'. This search is case sensitive.

Return values:

If the 'match' is found returns the zero based postion of the match.

If no 'match' is found returns STRERR_NOTFOUND.


str_locatei: (overloaded)

syntax:

int str_locatei(const STRING restrict s1, const STRING restrict s2 );
int str_locatei(const STRING restrict s1, const char * c );

str_locatei searches through object 's1' trying to find the same pattern of characters from object 's2' or array of chars * 'c'. This search is case sensitive.

Return values:

If the 'match' is found returns the zero based postion of the match.

If no 'match' is found returns STRERR_NOTFOUND.


str_lower:

syntax:

int str_lower( STRING restrict s );

str_lower converts any upper case characters in object 's' into lower case. The function operates on the string in-situ so previous data is destoryed.

Returns length of string.


str_msgbox:

syntax:

void str_msgbox( const STRING restrict s, const STRING restrict title, UINT uType );

str_msgbox calls the Windows API MessageBox( GetActiveWindow(), ...., uType ) placing string object 'title' in the caption and string object 's' as the body text.

uType
Specifies the contents and behavior of the dialog box. This parameter can be a combination of flags from the following groups of flags.

To indicate the buttons displayed in the message box, specify one of the following values.

Value Meaning
MB_ABORTRETRYIGNORE The message box contains three push buttons: Abort, Retry, and Ignore.
MB_CANCELTRYCONTINUE Windows 2000 or later: The message box contains three push buttons: Cancel, Try Again, Continue. Use this message box type instead of MB_ABORTRETRYIGNORE.
MB_HELP Windows 95/98, Windows NT 4.0 and later: Adds a Help button to the message box. When the user clicks the Help button or presses F1, the system sends a WM_HELP message to the owner.
MB_OK The message box contains one push button: OK. This is the default.
MB_OKCANCEL The message box contains two push buttons: OK and Cancel.
MB_RETRYCANCEL The message box contains two push buttons: Retry and Cancel.
MB_YESNO The message box contains two push buttons: Yes and No.
MB_YESNOCANCEL The message box contains three push buttons: Yes, No, and Cancel.

To display an icon in the message box, specify one of the following values.

Value Meaning
MB_ICONEXCLAMATION,
MB_ICONWARNING
An exclamation-point icon appears in the message box.
MB_ICONINFORMATION, MB_ICONASTERISK An icon consisting of a lowercase letter i in a circle appears in the message box.
MB_ICONQUESTION A question-mark icon appears in the message box.
MB_ICONSTOP,
MB_ICONERROR,
MB_ICONHAND
A stop-sign icon appears in the message box.

To indicate the default button, specify one of the following values.

Value Meaning
MB_DEFBUTTON1 The first button is the default button.

MB_DEFBUTTON1 is the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.

MB_DEFBUTTON2 The second button is the default button.
MB_DEFBUTTON3 The third button is the default button.
MB_DEFBUTTON4 The fourth button is the default button.

To indicate the modality of the dialog box, specify one of the following values.

Value Meaning
MB_APPLMODAL The user must respond to the message box before continuing work in the window identified by the hWnd parameter. However, the user can move to the windows of other threads and work in those windows.

Depending on the hierarchy of windows in the application, the user may be able to move to other windows within the thread. All child windows of the parent of the message box are automatically disabled, but popup windows are not.

MB_APPLMODAL is the default if neither MB_SYSTEMMODAL nor MB_TASKMODAL is specified.

MB_SYSTEMMODAL Same as MB_APPLMODAL except that the message box has the WS_EX_TOPMOST style. Use system-modal message boxes to notify the user of serious, potentially damaging errors that require immediate attention (for example, running out of memory). This flag has no effect on the user's ability to interact with windows other than those associated with hWnd.
MB_TASKMODAL Same as MB_APPLMODAL except that all the top-level windows belonging to the current thread are disabled if the hWnd parameter is NULL. Use this flag when the calling application or library does not have a window handle available but still needs to prevent input to other windows in the calling thread without suspending other threads.

To specify other options, use one or more of the following values.

Value Meaning
MB_DEFAULT_DESKTOP_ONLY Windows NT/2000 or later: Same as MB_SERVICE_NOTIFICATION except that the system will display the message box only on the default desktop of the interactive window station.

Windows NT 4.0 and earlier: If the current input desktop is not the default desktop, MessageBox fails.

Windows 2000 or later: If the current input desktop is not the default desktop, MessageBox does not return until the user switches to the default desktop.

Windows 95/98/Me: This flag has no effect.

MB_RIGHT The text is right-justified.
MB_RTLREADING Displays message and caption text using right-to-left reading order on Hebrew and Arabic systems.
MB_SETFOREGROUND The message box becomes the foreground window. Internally, the system calls the SetForegroundWindow function for the message box.
MB_TOPMOST The message box is created with the WS_EX_TOPMOST window style.
MB_SERVICE_NOTIFICATION Windows NT/2000 or later: The caller is a service notifying the user of an event. The function displays a message box on the current active desktop, even if there is no user logged on to the computer.

Terminal Services: If the calling thread has an impersonation token, the function directs the message box to the session specified in the impersonation token.

If this flag is set, the hWnd parameter must be NULL. This is so the message box can appear on a desktop other than the desktop corresponding to the hWnd.

For more information on the changes between Windows NT 3.51 and Windows NT 4.0, see Remarks.

MB_SERVICE_NOTIFICATION_NT3X Windows NT/2000 or later: This value corresponds to the value defined for MB_SERVICE_NOTIFICATION for Windows NT version 3.51.

For more information on the changes between Windows NT 3.51 and Windows NT 4.0, see Remarks.

Return Values

If the function succeeds, the return value is one of the following menu-item values.

Value Meaning
IDABORT Abort button was selected.
IDCANCEL Cancel button was selected.
IDCONTINUE Continue button was selected.
IDIGNORE Ignore button was selected.
IDNO No button was selected.
IDOK OK button was selected.
IDRETRY Retry button was selected.
IDTRYAGAIN Try Again button was selected.
IDYES Yes button was selected.

If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect.


str_new: (overloaded)

syntax:

STRING str_new( int buf_len );
STRING str_new( const char * s );

This creates a new STRING object.

Usage;
STRING a = str_new( 0 );
STRING b = str_new( "A quick brwon fox" );
STRING c = str_new( 40 );
char test[] = "A qiuck brwon fox";
STRING d = str_new( test );

or for an array of string objects:

STRING s[4];
for (int i =0; i<4; i++){
s[i] = str_new( 0 );
}

str_new creates a new string object and returns the pointer to the object. This pointer is used in all string library functions to reference the object. If buf_len is smaller than 20 bytes then the default size of 20 will be used.

Return values:

If successful a valid pointer to the new string object will be returned. If the function fails the function will return a NULL pointer. Use str_lasterror() to retrieve the error code. Either STRERR_MAXALLOCAT when string allocation has exceeded maximum allowed, or STRERR_MEMORY if memory allocation failed.


str_print:

syntax:

int str_print( STRING restrict s, BOOL nl = TRUE );

str_print sends the string of object 's' to stdout. Use 'nl' to determine if a new line character is appended. TRUE means that a new line will be appened, FALSE means a new line character will not be appended.

The 'nl' parametr defaults to TRUE so without suppling an argument it will print with a new line character appended. Examples:

str_print( mystr ); // this will print mystr and a new line char.

str_print( mystr , FALSE ); // this will not print a new line char.

The function returns the number of chars output. In the event of error it returns EOF. EOF is defined in stdio.h


str_printc:

syntax:

int str_printc( const char * s, BOOL nl = TRUE );

str_printc has been included for consistency. It works just as str_print but takes an array of chars as the first argument passed instead of a STRING object.

str_printc( "Hello!" ); // this will print mystr and a new line char.

str_printc( "Hello!", FALSE ); // this will not print a new line char.

The function returns the number of chars output. In the event of error it returns EOF. EOF is defined in stdio.h


str_printf:

syntax:

int str_printf( STRING restrict s, char * format, ... );

str_printf sends the string of object 's' to stdout with extra formated characters appened. Normal printf formating applies. See str_format for format specifiers.

Example:

STRING a = str_new( "The cat's age was " );
str_printf( a, " %d\n", 54 );

Output will be - "The cat's age was 54"

To format and print without a string object use:

str_printf( NULL, "%d\n", 54 );

Return value:

The number of characters output.


str_qsort:

syntax:

void str_qsort( STRING * restrict list, int nelem );

str_qsort sorts the array of string objects pointed to by 'list' case sensitive. 'nelem' is the number of array elements.

Example:

STRING s[4];
s[0] = str_new( "cat" );
s[1] = str_new( "elephant" );
s[2] = str_new( "hippopotamus" );
s[3] = str_new( "aardvark" );
str_qsort( &s[0], 4 );
str_print( s[0] );
str_print( s[1] );
str_print( s[2] );
str_print( s[3] );

The string object's indexs are also sorted. Let us assume that the strings index's are as follows:

String Index
cat 0
elephant 1
hippopotamus 2
aardvark 3

After sorting the strings the order of the index's have been moved to reflect the new order.

String Index
aardvark 0
cat 1
elephant 2
hippopotamus 3

Return values:

If successful str_qsort will return '1'. On error will return STRERR_MEMORY.


str_qsorti:

syntax:

void str_qsorti( STRING * restrict list, int nelem );

str_qsorti sorts the array of string objects pointed to by 'list' case in-sensitive. 'nelem' is the number of array elements.

Example:

STRING s[4];
s[0] = str_new( "cat" );
s[1] = str_new( "Elephant" );
s[2] = str_new( "Hippopotamus" );
s[3] = str_new( "aardvark" );
str_qsorti( &s[0], 4 );
str_print( s[0] );
str_print( s[1] );
str_print( s[2] );
str_print( s[3] );

The string object's indexs are also sorted. Let us assume that the strings index's are as follows:

String Index
cat 0
Elephant 1
Hippopotamus 2
aardvark 3

After sorting the strings the order of the index's have been moved to reflect the new order.

String Index
aardvark 0
cat 1
Elephant 2
Hippopotamus 3

Return values;

If successful str_qsorti will return '1'. On error will return STRERR_MEMORY.


str_remspace:

syntax:

int str_remspace( STRING src );
int str_remspace( const char * src );

str_remspace removes spaces from either a string object 'src' of an array of chars 'c'. Conversion is done in-situ so the original string will be overwritten.

Returns the number of spaces removed from the string object or array of chars.


str_resize:

syntax:

int str_resize( STRING restrict s, int size );

str_resize will attempt to grow the object 's' to the new length specified by 'size'. There is no facility to shrink a string object.

Returns the new size if successful. If the function fails, the return will be either STRERR_MEMORY when memory could not be reallocated or STRERR_SIZE if the requested size was greater than MAX_INT. If the requested size is smaller than current size there will be no allocation and the return will be the current size.

The original string characters will be unchanged.


str_rev:

syntax:

STRING str_rev( STRING restrict s );

str_rev reverses the string in object 's', this operation is carried out in in-situ. The terminating null character is not reversed.

Return Value:

str_rev returns a pointer to the string object 's'.


str_to_char:

syntax:

char * str_to_char( const STRING restrict s );

str_char will create a new array of chars and copy the string characters from object 's' to the new array.

Returns the pointer to new array of char if successful, otherwise a NULL pointer. Use str_lasterror() to retrieve the last error if the function fails. (STRERR_MEMORY)

The user is responsible for freeing the memory for the newly created array of chars.

Example:

STRING p = str_new( "A quick brown fox jumps over the lazy dog" );
char * m = str_to_char( p );
str_printc( m );
free(m);

str_token: (overloaded)

syntax:

int str_token( STRING dest, const STRING src, const STRING control );
int str_token( STRING dest, const STRING src, const char * control );
int str_token( STRING dest, const char * c, const char * control );

A sequence of calls to the str_token function breaks the string pointed to by 'src' into a sequence of tokens, each of which is delimited by a character from the string pointed to by 'control' and is copied to 'dest'.

The first call in the sequence has 'dest' as its first argument and 'src' as it's second argument, and is followed by calls with a NULL pointer as the second argument. The separator string pointed to by 'control' may be different from call to call.

Example:

STRING a = str_new( 20 );
STRING b = str_new( 20 );
str_char(a, "abc,d,efgh,jkl");

int n;

// str_token retruns the length of copied string
// and copies the string into object 'b' if found.
n = str_token( a , b , "," );
if ( n ){
str_print( b );
}
// second and subsequent calls to str_token using
// a NULL as the first parameter returns the position
// of the next token and copies that to object 'b'
while (n = str_token(NULL, b, ",")){
str_print( b );
}

Return values:

The length of each token is returned until no more tokens are found at which point zero is returned. Each deliminator found in the original string object is replaced with a NULL char.


str_upper:

syntax:

int str_upper( STRING restrict s );

str_upper converts any lower case characters in object 's' into upper case up to the null termination. The function operates on the string in-situ so previous data is destoryed.

Returns length of string.


str_xlate:

syntax:

int str_xlate( STRING restrict s, char * table );
int str_xlate( char * restrict c, char * table);

str_xlate replaces all the characters in string object 's' or array of chars 'c' using the values from a table of chars. The table array must be 256 characters in length as corresponds to the full range of char values.

Returns length of string.

Example:

char x[256];
int i;
for ( i = 0; i<256; i++ ) // first fill in all chars with values 0 to 255
x[i]= i;
 
for ( i = 65; i<91; i++ ) // then all upper case characters to lower case
x[i]= (i + 32);
 
for ( i = 97; i<123; i++ ) // then all lower case characters to upper case
x[i]= (i - 32);

char test[] = "A Quick Brown Fox Jumps Over The Lazy Dog";

str_copy( a, test );
str_xlate( a, x );

str_print( a );

str_xlate( test, x );
str_printc( test );

The example replaces all upper case characters in both string object 's' and array of chars 'c' with lower case and all lower case characters with upper case.