This article describes an implementation of the String Structure.
To program a String, we need to understand the interface of a String.
Structure of a String.
typedef struct String{ char * content; char * currentPositionPointer; unsigned int length; unsigned maxLength; } String;
A function that allocates a String structure and initializes it.
A function to allocate and initialize a String.
String * newString(){ String * string = (String *)malloc( sizeof( String ) ); if( string ){ string->content = 0; string->length = 0; string->maxLength = 1024; string->content = (char *)malloc( sizeof( char ) * string->maxLength ); if( !string->content ){ free( string ); return 0; } string->currentPositionPointer = string->content; } return string; }
A function to delete a String and free memory.
void deleteString( String * string ){ if( !string ){ return; } if( string->content ){ free( string->content ); } free( string ); }
The heart of all String operations. The function takes a character array and allocates more room for the String if the current one does not fit. Recall Strings are immutable objects.
Append to a String function.
int append( String * string, char * append, unsigned int count ){ char * newContent; if( !string ){ return -1; } if( !append ){ return 0; } if( count == 0 ){ return 0; } if( string->length + count > string->maxLength ){ string->maxLength = (string->length + count) * 2; newContent = (char *)malloc( sizeof( char ) * string->maxLength ); if( !newContent ){ return -2; } if( memcpy( newContent, string->content, 0, string->length ) != string->length ){ return -3; } free( string->content ); string->content = newContent; string->currentPositionPointer = string->content + string->length; } if( memcpy( string->currentPositionPointer, append, 0, count ) != count ){ return -4; } string->currentPositionPointer += count; return 0; }