Thursday, August 7, 2008

Making a String class in cpp

Program to manage strings(Source Code)
// Program Ch03pr01
// Program to manage strings

#include <string.h>
#include <iostream.h>
#include <conio.h>





const int MAX = 10 ;



class string

{

    private :



        char str[MAX] ;



    public :



        string( ) {}

        string ( char *s ) {strcpy(str,s);}

        int xstrlen( ) ;

        static void xstrcpy ( string &amp;t, string &amp;s ) ;

        static void xstrcat ( string &amp;t, string &amp;s ) ;

        static int xstrcmp ( string &amp;s1, string &amp;s2 ) ;

        void show( ) ;

} ;







// finds the length of the string

int string::xstrlen( )

{

    int l = 0 ;

    char *s = str ;

    while ( *s )

    {

        l++ ;

        s++ ;

    }

    return l ;

}



// copies source string s to the target string t

void string :: xstrcpy ( string &amp;t, string &amp;s )

{

    char *s1 = t.str ;

    char *s2 = s.str ;



    while ( *s2 )

    {

        *s1 = *s2 ;

        s1++ ;

        s2++ ;

    }

    *s1 = '\0' ;

}



// concatenates the two strings

void string :: xstrcat ( string &amp;t, string &amp;s )

{

    char *s1 = t.str ;

    char *s2 = s.str ;



    while ( *s1 )

        s1++ ;

    while ( *s2 )

        *s1++ = *s2++ ;

    *s1 = '\0' ;

}



// comapres two strings s1 and s2 for equality

int string :: xstrcmp ( string &amp;s1, string &amp;s2 )

{

    char *s = s1.str ;

    char *t = s2.str ;



    while ( *s == *t )

    {

        if ( ! ( *s ) )

            return 0 ;

        s++ ;

        t++ ;

    }

    return ( *s - *t ) ;

}



// displays the string

void string :: show( )

{

    cout &lt;&lt; str &lt;&lt; endl ;

}



int main( )

{

    string s1 ( "kicit" ) ;

    string s2 ( "Nagpur" ) ;



    cout &lt;&lt; endl ;

    cout &lt;&lt; "String s1: " ;

    s1.show( ) ;

    cout &lt;&lt; "\nLength of string s1: " &lt;&lt; s1.xstrlen( ) &lt;&lt; endl ;



    cout &lt;&lt; "\nString s2: " ;

    s2.show( ) ;



    string s3 ;

    string :: xstrcpy ( s3, s1 ) ;

    cout &lt;&lt; "\nString s3 after copying s1 to it: " ;

    s3.show( ) ;



    string :: xstrcat ( s3, s2 ) ;

    cout &lt;&lt; "\nString s3 after concatenation: " ;

    s3.show( ) ;



    if ( string :: xstrcmp ( s1, s2 ) == 0 )

        cout &lt;&lt; "\nThe strings s1 and s2 are similar" &lt;&lt; endl ;

    else

        cout &lt;&lt; "\nThe strings s1 and s2 are not similar" &lt;&lt; endl ;

        getch();

}

0 comments:

Post a Comment