Article 118 - String Implementation

This article describes an implementation of the String Structure.

For information about the String Structure, see Article 31 - Programming Data Structures.

To program a String, we need to understand the interface of a String.

Interface

  • New String
  • Delete String
  • Append String

Implementation

Structure of a String.

typedef struct String{
    char * content;
    char * currentPositionPointer;
    unsigned int length;
    unsigned maxLength;
} String;

New String Function

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;
}

Delete String Function

A function to delete a String and free memory.

void deleteString( String * string ){
    if( !string ){
        return;
    }

    if( string->content ){
        free( string->content );
    }

    free( string );
}

Append String Function

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;
}

Comments (0)

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.